Functional Power Tools: functools & itertools
Lesson 5 of 6 · View course roadmap
Learn the idea
Two standard-library modules hold the tools that make expert Python so compact:
functools — tools that operate on functions:
@lru_cache— memoize a function in one line; exponential recursions become instantreduce(f, seq)— fold a sequence into a single value:reduce(lambda a, b: a * b, [1, 2, 3, 4])→ 24partial(f, x)— pre-fill some arguments, get a new function back
itertools — an iterator algebra:
combinations("ABC", 2)— every unordered pairchain(a, b)— one stream from many iterablescount(),cycle(),islice()— infinite streams, safely sliced
Everything in itertools is lazy — these tools compose into data pipelines that process millions of items in constant memory.
Where you'll use this
@lru_cache turns expensive API lookups and recursive algorithms into O(1) repeats — it's a one-line performance patch used all over production code. itertools powers scheduling (cycle), pagination (islice), and combinatorics in testing and pricing engines.
Common mistakes
- Caching a function with mutable or unhashable arguments — @lru_cache needs hashable args and will TypeError on lists.
- Using reduce where sum(), max() or a comprehension is clearer — reduce is for genuinely custom folds, not a badge of honour.
- Printing an itertools result and seeing
<itertools.combinations object>— iterators must be consumed (list(), a loop) to see their values.
Pro tip
functools.partial shines with callbacks and key functions: sorted(rows, key=partial(score, weights=w)). It's cleaner than a lambda when you're just pinning arguments.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +45 XP
Use functools.reduce to print the product of the numbers 1–5. Then use itertools.combinations on the string "ABC" to print every 2-letter combination joined as a string, one per line.
120 AB AC BC
reduce(lambda a, b: a * b, range(1, 6)) gives the product. combinations("ABC", 2) yields tuples — join each with "".join(pair).
from functools import reduce
from itertools import combinations
print(reduce(lambda a, b: a * b, range(1, 6)))
for pair in combinations("ABC", 2):
print("".join(pair))
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.