Stop 08 · Intermediate PythonTopics · 7/10

itertools & functools

Part of the Python Roadmap

In short

Many loops you'd write by hand, like combining lists, grouping rows, trying every pair or caching slow results, already exist as fast, tested tools in itertools and functools.

itertools provides fast building blocks for loops, such as chain, groupby, combinations and islice. functools adds tools for functions, such as lru_cache for caching results, partial for pre-filling arguments and reduce.

The jaadu stands at a workbench choosing a shiny power drill from a pegboard full of neatly hung tools.

Think of it like this

Power tools vs hand tools

You can cut wood with a hand saw, but a carpenter reaches for the power saw because it's faster and cleaner. itertools and functools are power tools for loops and functions: same result, less effort, fewer mistakes.

Watch it happen

itertools.combinations(['Riya', 'Om', 'Zoya'], 2)

Riya
0
Om
1
Zoya
2

1/5We want every possible pair for a doubles match, without repeats.

The big ideas

What you need to know

chain and islice

chain(a, b) loops over several iterables as one. islice(it, 5) takes the first five items from any iterator.

groupby

Groups consecutive items with the same key. Sort by that key first, or groups get split.

combinations and product

combinations(items, 2) gives every pair, and product('AB', repeat=2) gives every ordered combination.

lru_cache, partial, reduce

@lru_cache remembers results of slow pure functions, partial pre-fills arguments, and reduce folds a list into one value.

See it in code

Walk through the code

python
1from functools import lru_cache, partial, reduce2from itertools import chain, combinations, groupby, islice3 4morning = ["idli", "poha"]5evening = ["samosa", "chai"]6print(list(chain(morning, evening)))7 8players = ["Riya", "Om", "Zoya"]9print(list(combinations(players, 2)))10 11sales = [("Delhi", 400), ("Delhi", 250), ("Goa", 900), ("Goa", 100)]12sales.sort(key=lambda s: s[0])13for city, rows in groupby(sales, key=lambda s: s[0]):14    print(city, sum(amount for _, amount in rows))15 16@lru_cache(maxsize=None)17def ways_to_climb(steps: int) -> int:18    if steps <= 1:19        return 120    return ways_to_climb(steps - 1) + ways_to_climb(steps - 2)21print(ways_to_climb(60))     # instant thanks to caching22 23to_inr = partial(round, ndigits=2)24print(to_inr(83.2567))       # 83.2625print(reduce(lambda a, b: a * b, [1, 2, 3, 4, 5]))   # 12026print(list(islice(chain(morning, evening), 3)))

1/7chain loops over both lists as if they were one, without building a combined list first.

Joining lists, every pair, totals per city, a cached recursive function and a few functools helpers.

Save yourself the pain

Common mistakes

Oops

Using groupby on unsorted data and getting the same city twice.

Do this instead

groupby only groups neighbours. Sort by the same key first.

Oops

Putting @lru_cache on a function that reads the clock or a database.

Do this instead

Only cache pure functions whose result depends only on their arguments.

Your mission

Tournament planner

~25 min

Quick check

Why must data usually be sorted before itertools.groupby?

Go deeper

  1. 1List all pairs of team members with itertools.combinations.
  2. 2Speed up a recursive Fibonacci function with @lru_cache.
  3. 3Use functools.partial to create a pre-configured version of a function.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge