from collections import defaultdict a = defaultdict(list) b = defaultdict(lambda: []) c = defaultdict(lambda: 0) # b[0]: [] # c[0]: 0 # c[1] += 1 => c[1] == 1
Counter
A dict to auto-count items.
1 2 3 4
from collections import Counter a = [1, 2, 3, 3] b = Counter(a) # b: Counter({3: 2, 1: 1, 2: 1})
More efficient way to code
for loop with value and index
1 2 3 4 5 6
# first way for i inrange(len(items)): pair = (i, items[i]) # second way: more efficient for i, v inenumerate(items): pair = (i, v)
don’t use len() in for loop
1 2 3 4 5 6 7
# first way for i inrange(len(items)): print(items[i]) # second way: more efficient n = len(items) for i inrange(n): print(items[i])
cache function value
@functools.cache(user_function) Simple lightweight unbounded function cache. Sometimes called “memoize”. Returns the same as lru_cache(maxsize=None), creating a thin wrapper around a dictionary lookup for the function arguments. Because it never needs to evict old values, this is smaller and faster than lru_cache() with a size limit. For example:
1 2 3 4 5
from functools import cache
@cache deffactorial(n): return n * factorial(n-1) if n else1