2. Iterators, Generators & Functional Tools
Functional Superpowers: functools & itertools
Speed up repeated calls with @lru_cache, specialize functions with partial(), and slice, chain, or combine iterables cleanly using Python's itertools module.
- Eliminate duplicate expensive function calls with @functools.cache and @lru_cache
- Pre-fill arguments cleanly using functools.partial
- Slice, flatten, and generate combinations lazily with itertools
Before writing a custom cache dictionary or nested for loops to combine lists, check Python's functools and itertools modules. They contain C-speed building blocks that pair naturally with generators and decorators.
Why It Matters: Before vs After
Consider flattening nested lists or generating combinations—writing manual cache dicts and nested loops quickly obscures your intent:
# Before: manual cache dictionary + boilerplate check
_fib_cache = {}
def fib_manual(n: int) -> int:
if n in _fib_cache:
return _fib_cache[n]
res = n if n < 2 else fib_manual(n - 1) + fib_manual(n - 2)
_fib_cache[n] = res
return res
# After: one-line declarative memoization with built-in eviction & stats
from functools import lru_cache
@lru_cache(maxsize=256)
def fib(n: int) -> int:
return n if n < 2 else fib(n - 1) + fib(n - 2)1. Instant Memoization with @cache & @lru_cache
When a pure function (same inputs always produce the same output, no side effects) is called repeatedly with overlapping inputs, @functools.lru_cache stores past results in an internal dictionary keyed by arguments:
from functools import lru_cache
@lru_cache(maxsize=256)
def fib(n: int) -> int:
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(40)) # Instant! Without caching this takes billions of calls.
print(fib.cache_info()) # CacheInfo(hits=38, misses=41, maxsize=256, currsize=41)Mental Model: Cache Keys & LRU Eviction
- LRU stands for Least Recently Used: once the cache hits
maxsize, the oldest unused entry is evicted so RAM stays bounded. - Use
@functools.cache(Python 3.9+) when inputs are small and bounded (same as@lru_cache(maxsize=None)). - Call
fib.cache_clear()in tests or when underlying data refreshes.
- Because
@lru_cachehashes arguments into a dictionary key, every argument must be hashable (int,str,tuple—neverlistordict). - Never cache functions that read live clocks, random numbers, or mutable databases unless you intentionally want stale cached outputs!
2. Pre-Filling Arguments with functools.partial
partial(func, *fixed_args, **fixed_kwargs) freezes selected arguments of a function and returns a clean, callable specialized version:
from functools import partial
def power(base: float, exp: float) -> float:
return base ** exp
square = partial(power, exp=2)
cube = partial(power, exp=3)
print(square(5)) # 25
print(cube(5)) # 125Unlike a lambda inside a loop (which suffers from late-binding closure bugs), partial captures its bound arguments immediately when created—making it ideal for callbacks, map(), sorting, and ThreadPoolExecutor tasks.
3. Lazy Combinators & Infinite Streams in itertools
Because itertools produces items on demand, you can even work with infinite generators like itertools.count(start, step) and safely slice just the first few items using islice():
from itertools import count, islice, product
# Infinite ID stream sliced lazily to first 4 IDs: [100, 102, 104, 106]
even_ids = list(islice(count(100, 2), 4))
# Replace nested loops with product()
grid_coords = list(product(["A", "B"], [1, 2])) # [('A', 1), ('A', 2), ('B', 1), ('B', 2)]Every function in itertools returns a lazy iterator—nothing is computed or copied into a big list until you consume it:
| Function | What it does | Example |
|---|---|---|
chain(a, b) | Loops through a, then b, without copying | list(chain([1, 2], [3, 4])) → [1, 2, 3, 4] |
chain.from_iterable(it) | Flattens one level lazily | list(chain.from_iterable([[1, 2], [3]])) → [1, 2, 3] |
islice(it, n) | Slices any iterator/generator safely | list(islice(gen, 5)) (first 5 items) |
batched(it, n) | Splits into tuples of size n (Python 3.12+) | list(batched("ABCDE", 2)) → [('A','B'), ('C','D'), ('E',)] |
combinations(it, r) | Unique subsets of length r (order ignored) | combinations(["A", "B", "C"], 2) → AB, AC, BC |
permutations(it, r) | Ordered arrangements of length r | permutations(["A", "B"], 2) → AB, BA |
product(a, b) | Cartesian product (replaces nested loops!) | product([1, 2], ["S", "M"]) |
groupby(it, key) | Groups consecutive equal keys | Must sort by key first! |
Unlike SQL GROUP BY, itertools.groupby(items, key=...) emits a new group every time the key changes! If your data isn't sorted by that exact key first, you'll get fragmented duplicate groups—either sort first or use collections.defaultdict(list).
Try It Yourself in the Playground
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Use itertools.product to print all 6 possible combinations of rolling two 6-sided dice whose sum equals 7.
Quick Checkpoints
Why did itertools.groupby([('A', 1), ('B', 2), ('A', 3)], key=lambda x: x[0]) create TWO separate 'A' groups?
Which value CANNOT be passed as an argument to a function decorated with @lru_cache?