Python Standard Library · Lesson 119 of 149

Python itertools

What you will learn

  • Why itertools exists: lazy building blocks (lesson 12.7)
  • Infinite iterators: count, cycle, repeat
  • Joining and slicing: chain, islice, zip_longest
  • Running results: accumulate, pairwise, batched
  • Grouping: groupby
  • Combinatorics: product, permutations, combinations

1. A toolbox for iterators

Lesson 12.4 introduced iterators: objects that give one item at a time. The itertools module is a collection of functions that create and combine iterators. They are lazy: they produce items only when asked, using very little memory, even for huge or infinite sequences. Most of them return an iterator, so wrap them in list(...) to see the contents.

import itertools as it

(Using the short alias it is common.)

2. Infinite iterators

print(list(it.islice(it.count(10, 5), 4)))
print(list(it.islice(it.cycle("ab"), 5)))
print(list(it.repeat("x", 3)))
[10, 15, 20, 25]
['a', 'b', 'a', 'b', 'a']
['x', 'x', 'x']
  • count(start, step) counts forever: 10, 15, 20, ...
  • cycle(items) repeats the items forever.
  • repeat(value, n) repeats a value (forever without n).

Never call list() on an infinite iterator: it would never finish. Use islice (next section) or a loop with break.

Quick check: why is `list(it.count())` a bad idea?

count() never ends, so the list would grow until memory runs out.

3. Joining and slicing

chain joins iterables one after another:

print(list(it.chain([1, 2], (3,), "ab")))
print(list(it.chain.from_iterable([[1, 2], [3], []])))
[1, 2, 3, 'a', 'b']
[1, 2, 3]

chain.from_iterable takes one iterable of iterables, the standard way to flatten one level of nesting (lesson 12.1).

islice slices any iterator, like list slicing but lazy (and no negative values):

print(list(it.islice(range(100), 2, 8, 2)))
print(list(it.islice("abcdef", 3)))
[2, 4, 6]
['a', 'b', 'c']

zip_longest zips to the longest input and fills the gaps (ordinary zip stops at the shortest, lesson 6.6):

print(list(it.zip_longest("abc", [1, 2], fillvalue="-")))
print(list(zip("abc", [1, 2])))
[('a', 1), ('b', 2), ('c', '-')]
[('a', 1), ('b', 2)]

4. Running results

accumulate gives running totals, or any running result with a function:

import operator

print(list(it.accumulate([1, 2, 3, 4])))
print(list(it.accumulate([1, 2, 3, 4], operator.mul)))
print(list(it.accumulate([3, 1, 4, 1, 5], max)))
print(list(it.accumulate([100, -30, 50], initial=0)))
[1, 3, 6, 10]
[1, 2, 6, 24]
[3, 3, 4, 4, 5]
[0, 100, 70, 120]

Sums (default), products, running maximum, and a balance starting from initial. pairwise (Python 3.10+) gives each neighbouring pair, perfect for differences:

print(list(it.pairwise([1, 4, 9, 16])))
print([b - a for a, b in it.pairwise([1, 4, 9, 16])])
[(1, 4), (4, 9), (9, 16)]
[3, 5, 7]

batched (Python 3.12+) cuts an iterable into tuples of a given size, the last one possibly shorter:

print(list(it.batched(range(7), 3)))
[(0, 1, 2), (3, 4, 5), (6,)]

(On older Python versions, use list(it.islice(...)) in a loop to the same effect.)

5. Selecting items

print(list(it.takewhile(lambda x: x < 4, [1, 2, 5, 1])))
print(list(it.dropwhile(lambda x: x < 4, [1, 2, 5, 1])))
print(list(it.filterfalse(str.isdigit, "a1b2")))
print(list(it.compress("abcd", [1, 0, 1, 0])))
[1, 2]
[5, 1]
['a', 'b']
['a', 'c']
  • takewhile takes items until the test first fails, then stops (even if later items would pass).
  • dropwhile skips items while the test is true, then takes everything after.
  • filterfalse is the opposite of filter: keeps items where the test is false.
  • compress(data, selectors) keeps items whose selector is true.

6. groupby

groupby(iterable, key) groups consecutive items that share the same key, giving (key, group) pairs. The word consecutive is the catch: it does not gather items from different places, so sort first by the same key:

data = [("fruit", "apple"), ("fruit", "pear"), ("veg", "kale"), ("fruit", "fig")]

for k, g in it.groupby(data, key=lambda r: r[0]):
    print(k, [x[1] for x in g])
print("sorted:")
for k, g in it.groupby(sorted(data), key=lambda r: r[0]):
    print(k, [x[1] for x in g])
fruit ['apple', 'pear']
veg ['kale']
fruit ['fig']
sorted:
fruit ['apple', 'fig', 'pear']
veg ['kale']

Without sorting, "fruit" appears twice, because veg split it. Another trap: each g is an iterator tied to the main one; use it before moving on (or convert it with list(g)). Run-length counting is a neat use:

print([(k, len(list(g))) for k, g in it.groupby("aaabbc")])
[('a', 3), ('b', 2), ('c', 1)]

For grouping an unsorted collection into a dictionary, defaultdict (lesson 17.3) is often simpler.

7. Combinatorics

Function Gives Example result for "abc"
product(a, b) every pairing (a "nested loop") ('a', 1), ('a', 2), ...
permutations(x, r) ordered arrangements 6 pairs from "abc", r=2
combinations(x, r) unordered selections ab ac bc
combinations_with_replacement(x, r) selections with repeats aa ab bb
print(list(it.product("ab", [1, 2])))
print(len(list(it.product(range(3), repeat=3))))
print(list(it.permutations("abc", 2)))
print(len(list(it.permutations(range(4)))))
print(list(it.combinations("abcd", 2)))
print(list(it.combinations_with_replacement("ab", 2)))
[('a', 1), ('a', 2), ('b', 1), ('b', 2)]
27
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
24
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
[('a', 'a'), ('a', 'b'), ('b', 'b')]
  • product(range(3), repeat=3) is 3 × 3 × 3 = 27 combinations, replacing three nested loops.
  • Permutations of 4 items: 4! = 24. The numbers explode: permutations of 8 items are 40,320 and of 12 items are over 479 million. These functions are lazy, but looping through all of them is still slow, so do not use them on large inputs.

8. Other useful tools

print(list(it.starmap(pow, [(2, 3), (3, 2)])))

a, b = it.tee([1, 2, 3])
print(list(a), list(b))

gen = (x * x for x in range(5))
print(list(gen), list(gen))
[8, 9]
[1, 2, 3] [1, 2, 3]
[0, 1, 4, 9, 16] []
  • starmap(f, rows) calls f(*row) for each row (a "map with unpacking").
  • tee(iterable, n) makes independent copies of one iterator.
  • The last pair of lines is a reminder: an iterator can be used only once (lesson 12.4). After list(gen), a second list(gen) is empty. tee or recreating the iterator is the cure.

Chunking a sequence without batched, on any Python 3 version:

def chunks(seq, n):
    items = iter(seq)
    while chunk := list(it.islice(items, n)):
        yield chunk

print(list(chunks("abcdefg", 3)))
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]

Worked example: menus, sales and pages

Find meals within a budget, summarise sorted sales by day, compute running totals and day-to-day changes, split a list into pages, and build codes.

from itertools import accumulate, batched, combinations, groupby, pairwise, product

menu = {"soup": 4, "salad": 5, "pasta": 9, "cake": 6, "tea": 2}
budget = 12
meals = [c for r in (2, 3) for c in combinations(menu, r)
         if sum(menu[i] for i in c) <= budget]
print(len(meals))
print(max(meals, key=lambda c: (sum(menu[i] for i in c), len(c))))

sales = [("Mon", 20), ("Mon", 35), ("Tue", 10),
         ("Wed", 5), ("Wed", 15), ("Wed", 25)]
for day, rows in groupby(sales, key=lambda r: r[0]):
    amounts = [a for _, a in rows]
    print(day, amounts, sum(amounts))

totals = [s for _, s in sales]
print(list(accumulate(totals)))
print([b - a for a, b in pairwise(totals)])

for page, items in enumerate(batched(menu, 2), start=1):
    print(page, items)

print(["".join(p) for p in product("AB", "12")])
9
('soup', 'cake', 'tea')
Mon [20, 35] 55
Tue [10] 10
Wed [5, 15, 25] 45
[20, 55, 65, 70, 85, 110]
[15, -25, -5, 10, 10]
1 ('soup', 'salad')
2 ('pasta', 'cake')
3 ('tea',)
['A1', 'A2', 'B1', 'B2']
Tool What it did
combinations(menu, r) every choice of 2 or 3 dishes (9 fit within 12 money units); the best fills the budget exactly with soup, cake and tea
groupby the sales were already in day order, so no sort was needed
accumulate, pairwise running total, and the change from one entry to the next
batched(menu, 2) the dish names (the keys) in pages of two
product all combinations of letters and digits

The menu and sales are made up. batched needs Python 3.12 or later.

Common mistakes

  • Calling list() on an infinite iterator.
  • Using groupby on unsorted data.
  • Reading a groupby group after advancing (convert with list(g)).
  • Reusing an exhausted iterator.
  • Expecting takewhile to skip failing items (it stops at the first failure).
  • Looping over permutations of a large input.
  • Using itertools when a simple loop or comprehension is clearer.

Key takeaways

  • itertools builds lazy iterators: count, cycle, repeat, chain, islice, zip_longest.
  • accumulate, pairwise and batched give running results, neighbouring pairs and chunks.
  • takewhile, dropwhile, filterfalse and compress select items.
  • groupby groups consecutive items: sort by the same key first.
  • product, permutations, combinations generate arrangements; the counts grow very fast.
  • Iterators run once; use tee or recreate them.

Practice

1. Write the first five multiples of 3 with itertools.

Show answer
list(it.islice(it.count(3, 3), 5))   # [3, 6, 9, 12, 15]

2. How do you flatten [[1, 2], [3], [4, 5]] into one list?

Show answer

list(it.chain.from_iterable(nested))

3. Why does groupby need sorted input?

Show answer

It groups only consecutive items with the same key, so equal keys in different places form separate groups.

4. How many ways to pick 2 of 5 items, order not mattering?

Show answer

10, which is len(list(it.combinations(range(5), 2))).

5. What is the difference between takewhile and filter?

Show answer

takewhile stops at the first item that fails the test; filter tests every item and keeps all that pass.

6. Why does a second list(gen) return an empty list?

Show answer

A generator is an iterator that can be consumed only once; after the first list it is exhausted.