
map() — apply function to every item:
numbers = [1, 2, 3, 4, 5] squares = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16, 25] # Prefer list comprehension: squares = [x**2 for x in numbers]
filter() — keep items matching condition:
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4] # Prefer: evens = [x for x in numbers if x % 2 == 0]
reduce() — aggregate to single value:
from functools import reduce total = reduce(lambda a, b: a + b, numbers) # 15 # Prefer: sum(numbers)
functools.lru_cache — memoization:
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
fibonacci(100) # instant, not exponentialpartial — pre-fill function arguments:
from functools import partial double = partial(lambda x, n: x * n, n=2) double(5) # 10
Reference:
TaskLoco™ — The Sticky Note GOAT