Write Better Python Code
Tags: python, productivity, codequality, programming
Published: 2021-12-29 15:38:11

## Introduction
This article has the collection python coding practices that I have learned over last few months for writing more idiomatic python code.

## 1. Multiple Assignment
Initialise same value for different variables.
```Python
# Instead of this
x = 10
y = 10
z = 10

# Use this
x = y = z = 10
```

## 2. Variable Unpacking
```Python
x, y = [1, 2]
# x = 1, y = 2

x, *y = [1, 2, 3, 4, 5]
# x = 1, y = [2, 3, 4, 5]

x, *y, z = [1, 2, 3, 4, 5]
# x = 1, y = [2, 3, 4], z = 5
``` 

## 3. Swapping Variables
```Python
# Instead of this
temp = x
x = y
y = temp

# Use this
x, y = y, x
```

## 4. Name Casing
In python `snake_case` is preferred over `camelCase` for variables and functions names.
```Python
# Instead of this
def isEven(num):
    pass

# Use this
def is_even(num):
    pass
```

## 5. Conditional Expressions
You can combine if-else statements into one line.
```Python
# Instead of this
def is_even(num):
    if num % 2 == 0:
        print("Even")
    else:
        print("Odd")

# Use this
def is_even(num):
    print("Even") if num % 2 == 0 else print("Odd")

# Or this
def is_even(num):
    print("Even" if num % 2 == 0 else "Odd")
```

## 6. String Formatting
```Python
name = "Dobby"
item = "Socks"

# Instead of this
print("%s likes %s." %(name, item))

# Or this
print("{} likes {}.".format(name, item))

# Use this
print(f"{name} likes {item}.")
```
f-strings are introduced in Python 3.6 and faster and more readable than other string formatting methods. 

## 7. Comparison Operator
```Python
# Instead of this
if 99 < x and x < 1000:
    print("x is a 3 digit number")

# Use this
if 99 < x < 1000:
    print("x is a 3 digit number")
```

## 8. Iterating over a list or tuple
We don't need to use indices to access list elements. Instead we can do this.
```Python
numbers = [1, 2, 3, 4, 5, 6]

# Instead of this
for i in range(len(numbers)):
    print(numbers[i])

# Use this
for number in numbers:
    print(number)

# Both of these yields the same output
```

## 9. Using enumerate()
When you need both indices and values, we can use `enumerate()`.
```Python
names = ['Harry', 'Ron', 'Hermione', 'Ginny', 'Neville']

for index, value in enumerate(names):
    print(index, value)
```

## 10. Using Set for searching
Searching in a set is faster(O(1)) compared to list(O(n)).
```Python
# Instead of this 
l = ['a', 'e', 'i', 'o', 'u']

def is_vowel(char):
    if char in l:
        print("Vowel")

# Use this
s = {'a', 'e', 'i', 'o', 'u'}

def is_vowel(char):
    if char in s:
        print("Vowel")
```

## 11. List comprehension
Consider the following program to multiply the elements of the list into 2 if they are even.
```Python
arr = [1, 2, 3, 4, 5, 6]
res = []

# Instead of this
for num in arr:
    if num % 2 == 0:
        res.append(num * 2)
    else:
        res.append(num)

# Use this
res = [(num * 2 if num % 2 == 0 else num) for num in arr]
```

## 12. Iterating Dictionary
Using `dict.items()` to iterate through a dictionary.
```Python
roll_name = {
    315: "Dharan",
    705: "Priya",
    403: "Aghil"
}

# Instead of this
for key in roll_name:
    print(key, roll_name[key])

# Do this
for key, value in roll_name.items():
    print(key, value)
```

### Sources

- [Do you write Python Code or Pythonic Code?](https://hub.packtpub.com/write-python-code-or-pythonic-code/)
- [Python 3's f-Strings](https://realpython.com/python-f-strings/)
- [Design Patterns in Python for the Untrained Eye](https://arielortiz.info/s201911/pycon2019/docs/design_patterns.html)
- [The Hitchhiker's Guide to Python](https://docs.python-guide.org/writing/style/)