Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Functional Power Tools: functools & itertools

16 min 45 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 5 of 6 · View course roadmap
Step 1

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 instant
  • reduce(f, seq) — fold a sequence into a single value: reduce(lambda a, b: a * b, [1, 2, 3, 4]) → 24
  • partial(f, x) — pre-fill some arguments, get a new function back

itertools — an iterator algebra:

  • combinations("ABC", 2) — every unordered pair
  • chain(a, b) — one stream from many iterables
  • count(), 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.

Step 2

Try it yourself

Blank · autosaved

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”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +45 XP

Blank · autosaved

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.

Target output
120
AB
AC
BC
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What does @lru_cache do?
2. Why is itertools memory-efficient?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path