Python Tips and Tricks You Didn’t Know You Needed: Boost Your Python Skills

Advanced Tips

  1. List of Lists Initialization
matrix = [[0]*5 for _ in range(5)]

2.Transpose a Matrix with zip()

transposed = list(zip(*matrix))

3. Unpack Function Arguments with *args and **kwargs

def my_func(*args, **kwargs):
    print(args, kwargs)

4. Use f-strings for String Formatting

name = 'Alice'
print(f'Hello, {name}')

5. Use defaultdict from collections

from collections import defaultdict
d = defaultdict(int)
d['missing'] += 1  # Automatically creates the key with a default value

6. Combine Lists with chain from itertools

from itertools import chain
combined = list(chain(list1, list2))

7. Check If All/Any Elements Match a Condition

all_even = all(x % 2 == 0 for x in my_list)

8. Use namedtuple for Lightweight Classes

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)

9. Measure Execution Time with timeit

import timeit
print(timeit.timeit("x = 2 + 2"))

10. Memoize with lru_cache

from functools import lru_cache
@lru_cache(maxsize=32)
def fibonacci(n):
    return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)

Leave a Comment