Write Better Python Code

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.

# Instead of this
x = 10
y = 10
z = 10

# Use this
x = y = z = 10

2. Variable Unpacking

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

# 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.

# 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.

# 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

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

# 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.

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().

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)).

# 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.

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.

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

32