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.

5 min readUpdated 2026-11-30
In This Lesson
  • 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:

python
# 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:

python
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.
Arguments Must Be Hashable (And Avoid Caching Side Effects!)
  1. Because @lru_cache hashes arguments into a dictionary key, every argument must be hashable (int, str, tuple—never list or dict).
  2. 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:

python
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))    # 125

Unlike 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():

python
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:

FunctionWhat it doesExample
chain(a, b)Loops through a, then b, without copyinglist(chain([1, 2], [3, 4])) → [1, 2, 3, 4]
chain.from_iterable(it)Flattens one level lazilylist(chain.from_iterable([[1, 2], [3]])) → [1, 2, 3]
islice(it, n)Slices any iterator/generator safelylist(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 rpermutations(["A", "B"], 2) → AB, BA
product(a, b)Cartesian product (replaces nested loops!)product([1, 2], ["S", "M"])
groupby(it, key)Groups consecutive equal keysMust sort by key first!
itertools.groupby() Only Groups Consecutive Items

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

Python 3Try It Live: functools & itertools
Output

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

Check Your Understanding

Why did itertools.groupby([('A', 1), ('B', 2), ('A', 3)], key=lambda x: x[0]) create TWO separate 'A' groups?

Check Your Understanding

Which value CANNOT be passed as an argument to a function decorated with @lru_cache?