10 Python Tricks That You Probably Should Know

Here you can find some Python tricks and tips that might be useful for your everyday coding.

1. List Comprehensions

List comprehensions are a concise way to create lists in Python. They are faster and better optimized than traditional for-loops and can be written in a single line of code.

squares = [x**2 for x in range(10)]

print(squares)

# Output:
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

2. Lambda functions

Lambda functions are small anonymous functions that can be defined in a single line of code. They are useful when you need a simple function for a short period of time. They can be used e.g. to provide a sorting function for the sort method of a list.

f = lambda x: x**2
print(f(2))
# Output: 4

people = [
    {
        'name': 'John',
    }, {
        'name': 'Lisa',
    }, {
        'name': 'Albreht',
    }
]

people.sort(key=lambda v: v['name'])
print(people)
# Output:
# [{'name': 'Albreht'}, {'name': 'John'}, {'name': 'Lisa'}]

3. Generators

Generators are functions that return an iterator. They are used to create large data sets that cannot be stored in memory all at once.

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
for i in range(10):
    print(next(fib))

# Output:
# 0
# 1
# 1
# 2
# 3
# 5
# 8
# 13
# 21
# 34

4. Context managers

Context managers are objects that define the behavior of the with statement. They are often used to manage resources such as files or network connections.

with open('file.txt', 'w') as f:
    f.write('Hello, world!')

with open('file.txt', 'r') as f:
    print(f.read())

# Output:
# Hello, world!

5. Decorators

Decorators are a way to modify or enhance the behavior of a function without changing its code. They are useful when you need to add functionality to multiple functions.

def debug(func):
    def wrapper(*args, **kwargs):
        print(f'Calling {func.__name__}()')
        return func(*args, **kwargs)
    return wrapper

@debug
def add(x, y):
    return x + y

result = add(2, 3)
print(result)

# Output:
# Calling add()
# 5

6. Tuple unpacking

Tuple unpacking is a way to assign multiple variables at once using a single tuple.

x, y = (1, 2)

print(x)
print(y)

# Output:
# 1
# 2

7. Zip function

The zip() function is used to combine two or more iterables into a single iterator of tuples.

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f'{name} is {age} years old')

# Output:
# Alice is 25 years old
# Bob is 30 years old
# Charlie is 35 years old

8. Defaultdict

The defaultdict is a dictionary-like object that provides a default value for non-existent keys.

from collections import defaultdict

colors = defaultdict(lambda: 'unknown')
colors['apple'] = 'red'

print(colors['apple'])
print(colors['banana'])

# Output:
# red
# unknown

9. Enumerate function

The enumerate() function is used to iterate over a sequence and keep track of the index of the current item.

fruits = ['apple', 'banana', 'cherry']

for i, fruit in enumerate(fruits):
    print(f'{i}: {fruit}')

# Output:
# 0: apple
# 1: banana
# 2: cherry

10. List slicing

List slicing is a way to extract a subset of elements from a list.

List slicing takes 3 parameters.

my_list[start, stop, step]

The start is the beginning of a slice, the stop is the end of a slice and the step is the step between the next numbers that are taken into the resulting list.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

print(numbers[:3])
# Output: [0, 1, 2]

print(numbers[-3:])
# Output: [10, 11, 12]

print(numbers[-1:])
# Output: [12]

print(numbers[::2])
# Output: [0, 2, 4, 6, 8, 10, 12]

print(numbers[::-1])
# Output: [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]