Skip to content

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.

Beginner 10 min read·Lesson 232 of 306 in Python Programming

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

Python
from itertools import islice, count, product, combinations, groupby, accumulate
list(islice(count(1), 5))
list(combinations("ABC", 2))
list(accumulate([1, 2, 3]))
  • Lazy and memory-efficient.
  • Limit infinite iterators.
  • Sort before groupby.

Code examples

Infinite iterators

Python
from itertools import count, cycle, islice, repeat
print(list(islice(count(10, 5), 4)))
print(list(islice(cycle("AB"), 5)))
print(list(repeat("x", 3)))
Output
[10, 15, 20, 25]
['A', 'B', 'A', 'B', 'A']
['x', 'x', 'x']

Combinatorics

Python
from itertools import combinations, permutations, product
print(list(product("ab", [1, 2])))
print(len(list(permutations(range(4), 2))), list(combinations("ABC", 2)))
Output
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]
12 [('A', 'B'), ('A', 'C'), ('B', 'C')]

More examples

Grouping, totals, pairs and batches

Python
from itertools import accumulate, batched, chain, groupby, pairwise
sales = [("Mon", 120), ("Mon", 80), ("Tue", 200), ("Wed", 50), ("Wed", 70)]
for day, rows in groupby(sales, key=lambda r: r[0]):
print(day, sum(v for _, v in rows))
print(list(accumulate([3, 1, 4, 1, 5])))
print(list(chain([1, 2], (3,), "ab")))
print([b - a for a, b in pairwise([10, 13, 19, 20])])
print(list(batched(range(7), 3)))
Output
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:

TextOutput
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,)]

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

groupby(["a", "b", "a"]) # 'a' appears twice

Prefer

groupby(sorted(["a", "b", "a"]))

groupby only groups consecutive equal keys.

Consuming an iterator twice

Avoid

pairs = combinations(xs, 2)
print(list(pairs))
print(len(list(pairs))) # 0

Prefer

pairs = list(combinations(xs, 2))

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

  1. 1
    List every 2-topping pizza from five toppings using combinations.
  2. 2
    Compute 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?
Practise this topic