Module 15 · Python Standard Libraries — topic 11 of 13
itertools
Efficient iterator building blocks: infinite iterators (count, cycle, repeat), islice, combinatorics (product, permutations, combinations), grouping with groupby, running totals with accumulate, chain, pairwise and batched.
Learning objectives
- Use infinite iterators safely with islice
- Generate combinations and permutations
- Group, accumulate, chain and batch data
Definition
itertools provides fast, memory-efficient functions that create and combine iterators. They produce values lazily, so even infinite or very large sequences can be processed step by step.
Introduction
Every password of 3 letters, all pairs of players, running bank balances, data in chunks of 100 — itertools turns such tasks into one-liners.
Why it matters
itertools functions are written in C, use little memory and express intent clearly, replacing nested loops and manual bookkeeping.
Detailed explanation
count(start, step), cycle(iterable) and repeat(value, n) produce endless (or long) streams; limit them with islice or zip.
islice(iterable, stop) or islice(iterable, start, stop, step) slices any iterator lazily.
product(a, b) gives the Cartesian product (like nested loops); permutations(items, r) ordered arrangements; combinations(items, r) unordered selections.
groupby(data, key) groups consecutive items with the same key — sort the data by that key first if groups aren't already together.
accumulate(values) gives running totals (or running results of any two-argument function).
chain(a, b, ...) joins iterables; pairwise(xs) yields neighbouring pairs; batched(xs, n) (Python 3.12+) yields tuples of up to n items.
Results are iterators: wrap them in list() to see all values, and remember they can only be consumed once.
Combinatoric results grow very quickly: permutations of 10 items gives over 3.6 million tuples. Iterate over them lazily rather than building a list.
Syntax
- Lazy and memory-efficient.
- Limit infinite iterators.
- Sort before groupby.
Code examples
Infinite iterators
[10, 15, 20, 25] ['A', 'B', 'A', 'B', 'A'] ['x', 'x', 'x']
Combinatorics
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]
12 [('A', 'B'), ('A', 'C'), ('B', 'C')]More examples
Grouping, totals, pairs and batches
Mon 200 Tue 200 Wed 120 [3, 4, 8, 9, 14] [1, 2, 3, 'a', 'b'] [3, 6, 1] [(0, 1, 2), (3, 4, 5), (6,)]
Step-by-step explanation
- groupby works because the sales are already ordered by day.
- accumulate produces running totals; pairwise makes computing differences between neighbours easy.
- batched splits data into chunks, with a shorter final chunk.
Expected output
Running “Grouping, totals, pairs and batches” prints exactly:
Practical applications
- Generating test cases from all combinations of options.
- Processing database rows in batches.
Best practices
- Limit infinite iterators with islice.
- Sort by the key before groupby.
- Convert to a list only when you need all values at once.
Common mistakes
groupby on unsorted data
Avoid
Prefer
groupby only groups consecutive equal keys.
Consuming an iterator twice
Avoid
Prefer
Iterators are exhausted after one pass.
Important notes
- The itertools documentation includes a 'recipes' section of useful combinations of these tools.
Key takeaways
- itertools builds efficient lazy iterators.
- product, permutations and combinations generate arrangements.
- groupby, accumulate, chain, pairwise and batched process streams.
Try it yourself
- 1List every 2-topping pizza from five toppings using combinations.
- 2Compute a running balance from a list of deposits and withdrawals with accumulate.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
2 questions test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?
- ModerateWhat is printed?