Python: How to...
Tags: python, beginners
Published: 2020-06-21 17:43:06

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?](#question-1)
* [2. How to swap contents of two variables?](#question-2)
* [3. How to use f-strings for formatting?](#question-3)
* [4. How to print a numbered list?](#question-4)
* [5. How to print Emojis in Python?](#question-5)
* [6. How to reverse a String in a succinct way?](#question-6)
* [7. How to remove duplicates from the list?](#question-7)
* [8. How to iterate over multiple lists at once?](#question-8)
* [9. How to pack / unpack elements?](#question-9)
* [10. How to merge two dictionaries?](#question-10)
* [11. How to efficiently work with resources?](#question-11)
* [12. How to check whether all elements of one list is in another list?](#question-12)

<a name="question-1"></a>
### 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:
```python
x, y = 10, 20

max = x if x > y else y

print(max)
```

<a name="question-2"></a>
### 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.
```python
s1 = "Hello"
s2 = "Goodbye"

s2, s1 = s1, s2

print(s2)  # Hello
print(s1)  # Goodbye
```

<a name="question-3"></a>
### 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. 
```python
s = "World"
# formatting using format method
print("Hello {0}!".format(s))    # Hello World!
# format using f-string
print(f"Hello {s}!")   # Hello World!
```
<a name="question-4"></a>
### 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:
```python
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
```

<a name="question-5"></a>
### 5. How to print Emojis in Python?
```python
import emoji
today = "Weather is :sunny: today! I :heart: it!"
print(emoji.emojize(today, use_aliases=True))

# Output
# Weather is ☀ today! I ❤ it!
```

<a name="question-6"></a>
### 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. 
```python
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
```

<a name="question-7"></a>
### 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. 
```python
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]
```

<a name="question-8"></a>
### 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.
```python
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    
```
<a name="question-9"></a>
### 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. 
```python
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    
```
**Unpacking** is the reverse of packing in which if a function expects multiple parameters, a sequence can be unpacked to supply argument values.
```python
def avg(a, b, c):
    return (a + b + c) / 4

print(f"Average = {avg(*[10, 20, 30])}")  # Average = 15.0
```
<a name="question-10"></a>
### 10. How to merge two dictionaries?
We could unpack individual elements of two dictionaries and merge them. To unpack dictionaries `**` are used.
```python
d1={'Apple' : 5}
d2={'Orange' : 4, 'Banana' : 3}
result = {**d1,**d2}  
print(result)  # {‘Apple’ : 5, ‘Orange’: 4, ‘Banana’: 3}
```
<a name="question-11"></a>
### 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.
```python
with open('hello.txt', 'wt') as f:
    f.write("Hello World!")
```  
<a name="question-12"></a>
### 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.

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

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

print(result) # True
```