DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 967,911 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Python: How to...
dev0928
dev0928

Posted on

Python: How to...

Programming language is considered very powerful if it can solve a given set of problems succinctly and efficiently. In this article, let’s see how Python can solve a series of problems concisely using a set How to questions.

1. How to use ternary operator?

Python's ternary operator provides a succinct way to choose values based on a condition. It is of format - result = <true value> if <condition> else <false value>. Below program returns max of two numbers using ternary operator:

x, y = 10, 20

max = x if x > y else y

print(max)
Enter fullscreen mode Exit fullscreen mode

2. How to swap contents of two variables?

Generally when contents of variables have to be swapped, a temporary variable is required to hold one of the values being swapped. But in Python, temporary storage is not needed for swapping values.

s1 = "Hello"
s2 = "Goodbye"

s2, s1 = s1, s2

print(s2)  # Hello
print(s1)  # Goodbye
Enter fullscreen mode Exit fullscreen mode

3. How to use f-strings for formatting?

Python 3.6 introduced f-strings to format strings which allows variables to be in-lined within the formatted string resulting in more readable formatted string.

s = "World"
# formatting using format method
print("Hello {0}!".format(s))    # Hello World!
# format using f-string
print(f"Hello {s}!")   # Hello World!
Enter fullscreen mode Exit fullscreen mode

4. How to print a numbered list?

If we want to print list of items along with their sequential numbers, we could use enumerate function like shown below:

fruits = ["Apple", "Banana", "Pear", "Orange", "Strawberry"]
for idx, fruit in enumerate(fruits, 1):
    print(f"{idx}. {fruit}")

# Output
# 1. Apple
# 2. Banana
# 3. Pear
# 4. Orange
# 5. Strawberry
Enter fullscreen mode Exit fullscreen mode

5. How to print Emojis in Python?

import emoji
today = "Weather is :sunny: today! I :heart: it!"
print(emoji.emojize(today, use_aliases=True))

# Output
# Weather is β˜€ today! I ❀ it!
Enter fullscreen mode Exit fullscreen mode

6. How to reverse a String in a succinct way?

Strings could be reversed in multiple ways. Below example takes advantage of the fact that individual string's characters can be iterated like any other sequence and iterates it from the end to beginning resulting in reversed string.

def is_palindrome(word):
    return True if word == word[::-1] else False

s = "Hello"
print(s)  # Hello
# Reverse the string
print(s[::-1])  # olleH
print(is_palindrome(s))  # False

w = "racecar"
print(is_palindrome(w))  # True
Enter fullscreen mode Exit fullscreen mode

7. How to remove duplicates from the list?

Below duplication removal method takes advantage of the fact that sets data structure cannot contain duplicates. So, when the list object containing duplicates is used to create a set object, duplicates are removed in the target set resulting in automatic removal of duplicates.

nums = [1, 5, 22, 30, 15, 12, 33, 15, 22, 1]
# converting list to set removes the duplicate items
unums = list(set(nums))
# Original list
print(nums)    # [1, 5, 22, 30, 15, 12, 33, 15, 22, 1]
# unique list
print(unums)  # [1, 33, 5, 12, 15, 22, 30]
Enter fullscreen mode Exit fullscreen mode

8. How to iterate over multiple lists at once?

Python has a powerful function called zip that allows two or more sequences to be iterated and paired at once. Below program is pairing days to the corresponding temperatures.

days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday']
temps = [90, 88, 87, 89]
for d, w in zip(days, temps):
    print(f"{d}'s temperature is {w}")

# Output
# Sunday's temperature is 90
# Monday's temperature is 88
# Tuesday's temperature is 87
# Wednesday's temperature is 89    
Enter fullscreen mode Exit fullscreen mode

9. How to pack / unpack elements?

Packing is a technique in which if a function expects variable number of arguments, they all could be collected into a single tuple using *<param_name> syntax.

def add_nums(*args):
    sum = 0
    for num in args:
        sum += num
    return sum

print(f"Sum = {add_nums(3, 5, 7, 9)}")    # Sum = 24    
Enter fullscreen mode Exit fullscreen mode

Unpacking is the reverse of packing in which if a function expects multiple parameters, a sequence can be unpacked to supply argument values.

def avg(a, b, c):
    return (a + b + c) / 4

print(f"Average = {avg(*[10, 20, 30])}")  # Average = 15.0
Enter fullscreen mode Exit fullscreen mode

10. How to merge two dictionaries?

We could unpack individual elements of two dictionaries and merge them. To unpack dictionaries ** are used.

d1={'Apple' : 5}
d2={'Orange' : 4, 'Banana' : 3}
result = {**d1,**d2}  
print(result)  # {β€˜Apple’ : 5, β€˜Orange’: 4, β€˜Banana’: 3}
Enter fullscreen mode Exit fullscreen mode

11. How to efficiently work with resources?

When working with resources like files care must be taken to close them at the end of its use. We could end up with unforeseen results if the close <resource> statement is forgotten. Opening a file using with context manager solves this problem by auto closing the resource at the end of its use.

with open('hello.txt', 'wt') as f:
    f.write("Hello World!")
Enter fullscreen mode Exit fullscreen mode

12. How to check whether all elements of one list is in another list?

Another great example of how Python can solve a relatively complex problem with a single line of code. We could also use any to check whether any of the elements are in another list.

list1 = ['Hi' ,  'hello', 'master', 'world', 'list']
list2 = ['world' , 'hello', 'Hi']

result = all(elem in list1 for elem in list2)

print(result) # True
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
renegadecoder94 profile image
Jeremy Grifski

I'm oddly excited about the possibility of a dictionary union operator in Python 3.9. I think that'll make the solution to 10 even cleaner:

result = d1 | d2

Here's the PEP for it.

Collapse
 
idimaimuna profile image
M__

This is very helpful. Thanks for sharing

Collapse
 
sanyaldips93 profile image
Dipayan Sanyal

This is so well put.

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.