A college canteen sells 3 sizes of chai and 4 snacks, and wants to print every possible combo for a menu board. A cricket coach needs every possible pair of openers from 6 batters. A shop wants a running total of today's sales after every bill. You could write nested loops and counters for each of these, but Python already has fast, tested tools for them in the Python itertools module.
itertools is a standard library module of functions that build and combine iterators. They're lazy, so they work on huge or endless data, and most replace a loop you'd otherwise write by hand. This lesson covers the ones you'll actually use, grouped by job, with examples you can run.
What you need first: Python iterators and iterables, Python generators and lambda, map, filter and sorted.
Key terms
- itertools: a built-in module of tools that create and combine iterators. Import it with
import itertoolsorfrom itertools import .... - Infinite iterator: an iterator that never runs out, such as a counter. You must stop it yourself.
- Cartesian product: every way to pick one item from each of several groups, like every (size, snack) pair.
- Permutation: an arrangement where order matters: AB and BA are different.
- Combination: a selection where order doesn't matter: AB and BA are the same.
Every itertools function returns an iterator. To see the values, the examples wrap them in list(). In real code you'll often loop over them directly.
Infinite iterators: count, cycle and repeat
count(start, step) counts for ever. It's useful for numbering things when you don't know how many there will be:
from itertools import count
for token, name in zip(count(101), ["Ahana", "Rohan", "Meera"]):
print(token, name)
101 Ahana
102 Rohan
103 Meera
zip stops at the shortest input, so the endless counter stops after the third name.
cycle(iterable) repeats a sequence for ever, such as rotating duty shifts:
from itertools import cycle
shifts = cycle(["Morning", "Evening"])
staff = ["Ahana", "Rohan", "Meera", "Dev", "Sara"]
for person in staff:
print(person, next(shifts))
Ahana Morning
Rohan Evening
Meera Morning
Dev Evening
Sara Morning
repeat(value, times) gives the same value again and again, a set number of times or for ever if you leave out times.
Taking part of an iterator: islice
You can't slice an iterator with [ ]. islice(iterable, stop) or islice(iterable, start, stop, step) does the same job lazily:
from itertools import count, islice
print(list(islice(count(0, 5), 4)))
print(list(islice(range(100), 10, 20, 3)))
[0, 5, 10, 15]
[10, 13, 16, 19]
islice is the safe way to take the first few values from an infinite generator, such as the Fibonacci generator from the last lesson.
Joining iterables: chain
chain walks through several iterables one after another, without building a new combined list:
from itertools import chain
section_a = ["Ahana", "Dev"]
section_b = ("Meera",)
section_c = ["Rohan", "Sara"]
print(list(chain(section_a, section_b, section_c)))
nested = [[1, 2], [3], [4, 5]]
print(list(chain.from_iterable(nested)))
['Ahana', 'Dev', 'Meera', 'Rohan', 'Sara']
[1, 2, 3, 4, 5]
chain.from_iterable flattens one level of nesting. It's faster and clearer than sum(nested, []), which beginners sometimes use.
Running totals: accumulate
accumulate gives running results: the total after each item. Think of a bank passbook, where each row shows the balance after that transaction:
from itertools import accumulate
transactions = [5000, -1200, -800, 3000, -450]
print(list(accumulate(transactions)))
print(list(accumulate(transactions, initial=10000)))
[5000, 3800, 3000, 6000, 5550]
[10000, 15000, 13800, 13000, 16000, 15550]
Pass a function as the second argument to accumulate something other than a sum. With max, you get the highest value so far, such as a batter's best score after each match:
from itertools import accumulate
scores = [34, 12, 78, 45, 101, 9]
print(list(accumulate(scores, max)))
[34, 34, 78, 78, 101, 101]
Grouping: groupby
groupby groups neighbouring items that share a key. Here, total sales per city:
from itertools import groupby
sales = [("Pune", 100), ("Delhi", 50), ("Pune", 30), ("Delhi", 20), ("Goa", 70)]
sales.sort(key=lambda s: s[0]) # sort by the same key first
for city, rows in groupby(sales, key=lambda s: s[0]):
print(city, sum(amount for _, amount in rows))
Delhi 70
Goa 70
Pune 130
You must sort by the same key first. This is the single biggest groupby trap. Without sorting, groupby starts a new group every time the key changes:
from itertools import groupby
print([(key, len(list(group))) for key, group in groupby("aabbbaa")])
[('a', 2), ('b', 3), ('a', 2)]
That "group every run" behaviour is sometimes exactly what you want, such as counting streaks of wins and losses. For totals per category, sort first, or use a dictionary or pandas' groupby, which don't need sorting.
Combinatorics: product, permutations and combinations
These four answer "how many ways are there?" questions, and list every way.
product: one from each group
from itertools import product
sizes = ["Small", "Large"]
snacks = ["Samosa", "Vada pav", "Poha"]
for size, snack in product(sizes, snacks):
print(f"{size} chai + {snack}")
Small chai + Samosa
Small chai + Vada pav
Small chai + Poha
Large chai + Samosa
Large chai + Vada pav
Large chai + Poha
product replaces nested for loops. With repeat=, it picks from the same group several times, like every 3-digit binary string:
from itertools import product
print(["".join(bits) for bits in product("01", repeat=3)])
['000', '001', '010', '011', '100', '101', '110', '111']
permutations: arrangements where order matters
from itertools import permutations
print(["".join(p) for p in permutations("ABC", 2)])
['AB', 'AC', 'BA', 'BC', 'CA', 'CB']
Use it for things like "captain and vice-captain" from a group, where Ahana as captain with Rohan as vice-captain differs from the other way round.
combinations: selections where order doesn't matter
from itertools import combinations
batters = ["Rohit", "Gill", "Kohli", "Iyer"]
for pair in combinations(batters, 2):
print(pair)
('Rohit', 'Gill')
('Rohit', 'Kohli')
('Rohit', 'Iyer')
('Gill', 'Kohli')
('Gill', 'Iyer')
('Kohli', 'Iyer')
An opening pair of Rohit and Gill is the same pair as Gill and Rohit, so it's listed once. combinations_with_replacement also allows picking the same item twice, like two scoops of the same ice-cream flavour.
How many results to expect
Choosing r items from n:
| Function | Order matters? | Repeats allowed? | Count for n = 4, r = 2 |
|---|---|---|---|
product(items, repeat=r) | Yes | Yes | 4² = 16 |
permutations(items, r) | Yes | No | 4 × 3 = 12 |
combinations(items, r) | No | No | 6 |
combinations_with_replacement(items, r) | No | Yes | 10 |
The math module calculates these counts without listing anything: math.perm(4, 2) is 12 and math.comb(4, 2) is 6. The counts grow very fast, so check them before listing: permutations(range(12)) has about 48 crore arrangements.
import math
from itertools import combinations, permutations
print(len(list(permutations(range(4), 2))), math.perm(4, 2))
print(len(list(combinations(range(4), 2))), math.comb(4, 2))
print(math.comb(49, 6))
12 12
6 6
13983816
There are almost 1.4 crore ways to choose 6 numbers from 49, which is why lotteries are hard to win. Probability is built on counts like these; the maths foundations course starts from the basics.
Zipping lists of different lengths: zip_longest
zip stops at the shortest list. zip_longest keeps going and fills the gaps:
from itertools import zip_longest
students = ["Ahana", "Rohan", "Meera"]
marks = [88, 72]
print(list(zip(students, marks)))
print(list(zip_longest(students, marks, fillvalue="absent")))
[('Ahana', 88), ('Rohan', 72)]
[('Ahana', 88), ('Rohan', 72), ('Meera', 'absent')]
Filtering: takewhile, dropwhile and compress
takewhile takes items while a condition is true and stops at the first failure. dropwhile skips items while it's true, then gives everything else:
from itertools import takewhile, dropwhile
temps = [22, 25, 29, 31, 27, 24]
print(list(takewhile(lambda t: t < 30, temps)))
print(list(dropwhile(lambda t: t < 30, temps)))
[22, 25, 29]
[31, 27, 24]
Unlike filter, these stop checking after the first change: 27 and 24 are below 30 but aren't taken, because takewhile already stopped at 31.
compress keeps items where a matching selector is true:
from itertools import compress
names = ["Ahana", "Rohan", "Meera", "Dev"]
present = [1, 0, 1, 1]
print(list(compress(names, present)))
['Ahana', 'Meera', 'Dev']
Neighbours and chunks: pairwise and batched
pairwise (Python 3.10 and newer) gives each item with the next one, which is perfect for day-to-day changes:
from itertools import pairwise
closing_prices = [100, 120, 90, 150]
changes = [b - a for a, b in pairwise(closing_prices)]
print(changes)
[20, -30, 60]
batched (Python 3.12 and newer) splits an iterable into chunks of a fixed size, the last one possibly smaller:
from itertools import batched
print(list(batched(range(1, 8), 3)))
[(1, 2, 3), (4, 5, 6), (7,)]
Batching is how you send 1,000 emails in groups of 80, or feed data to a model in mini-batches. On older Python versions, use the batches generator from the generators lesson.
starmap
starmap is like map, but each item is a tuple of arguments, unpacked into the function:
from itertools import starmap
orders = [(2, 40), (1, 120), (3, 15)] # (quantity, unit price)
print(list(starmap(lambda qty, price: qty * price, orders)))
[80, 120, 45]
Quick reference
| Job | Function |
|---|---|
| Number items for ever | count(start, step) |
| Repeat a sequence for ever | cycle(items) |
| Take part of an iterator | islice(it, start, stop, step) |
| Join iterables end to end | chain(a, b), chain.from_iterable(nested) |
| Running totals or maximums | accumulate(items, func) |
| Group neighbouring items (sort first) | groupby(items, key) |
| Every combination of one from each | product(a, b), product(a, repeat=n) |
| Ordered arrangements | permutations(items, r) |
| Unordered selections | combinations(items, r) |
| Zip uneven lists | zip_longest(a, b, fillvalue=...) |
| Take or skip while a condition holds | takewhile, dropwhile |
| Each item with the next | pairwise(items) |
| Fixed-size chunks | batched(items, n) |
The official documentation (docs.python.org/3/library/itertools.html) also has a "recipes" section with more tools built from these.
Where itertools is used
- Testing:
productgenerates every combination of settings to test. - Data analysis:
accumulatefor running totals,pairwisefor changes between readings,groupbyon sorted logs. - Machine learning: trying every combination of model settings (a grid search) is a
product; scikit-learn'sParameterGriddoes the same thing. - Interviews and competitive programming: permutations and combinations for brute-force solutions on small inputs.
Common mistakes
groupbywithout sorting by the same key first, which gives repeated groups.- Using a
groupbygroup after moving on. Each group is an iterator that's used up when you go to the next key; convert it withlist()straight away if you need to keep it. list()on an infinite iterator likecount()orcycle(). Useisliceorzipto stop it.- Listing huge numbers of permutations. Check the count with
math.permormath.combfirst. - Reusing an itertools result. Like all iterators, it's used up after one pass.
Practice
- List every 2-character code from the letters
"XY"and digits"12", letter first.
Show the answer
from itertools import product
print([a + b for a, b in product("XY", "12")])
['X1', 'X2', 'Y1', 'Y2']
- Daily sales were
[1200, 950, 1430, 800, 1600]. Print the running total after each day.
Show the answer
from itertools import accumulate
print(list(accumulate([1200, 950, 1430, 800, 1600])))
[1200, 2150, 3580, 4380, 5980]
- In how many ways can a committee of 3 be chosen from 10 students? Check by listing and with
math.comb.
Show the answer
import math
from itertools import combinations
print(len(list(combinations(range(10), 3))), math.comb(10, 3))
120 120
10 × 9 × 8 ÷ (3 × 2 × 1) = 120.
- Group these words by their first letter.
words = ["mango", "apple", "melon", "avocado", "banana"]
Show the answer
Sort by the first letter, then group by it:
from itertools import groupby
words = ["mango", "apple", "melon", "avocado", "banana"]
first = lambda w: w[0]
for letter, group in groupby(sorted(words, key=first), key=first):
print(letter, list(group))
a ['apple', 'avocado']
b ['banana']
m ['mango', 'melon']
- Print the first 6 values of
count(1)that are divisible by 7, without a loop that you break out of yourself.
Show the answer
Filter the endless counter, then take 6 with islice:
from itertools import count, islice
sevens = (n for n in count(1) if n % 7 == 0)
print(list(islice(sevens, 6)))
[7, 14, 21, 28, 35, 42]
- Find the longest streak of wins in
"WWLWWWLLW".
Show the answer
Here groupby without sorting is exactly right, because a streak is a run of neighbouring items:
from itertools import groupby
results = "WWLWWWLLW"
print(max(len(list(g)) for k, g in groupby(results) if k == "W"))
3
Interview questions
What is the difference between permutations and combinations in itertools?
permutations(items, r) gives ordered arrangements, so ('A', 'B') and ('B', 'A') are both included. combinations(items, r) gives unordered selections, so each group appears once. For 4 items taken 2 at a time there are 12 permutations and 6 combinations.
Why must data be sorted before using itertools.groupby?
groupby only groups consecutive items with the same key; it starts a new group whenever the key changes. If equal keys aren't next to each other, the same key appears in several groups. Sorting by the same key puts equal keys together.
How do you flatten a list of lists efficiently?
list(itertools.chain.from_iterable(list_of_lists)), or a comprehension [x for sub in list_of_lists for x in sub]. Both are linear time. sum(list_of_lists, []) works but is quadratic, because it builds a new list at every step.
Key takeaways
- itertools functions return lazy iterators; wrap them in
list()to see the values. count,cycleandrepeatare endless; stop them withzip,isliceorbreak.chainjoins,accumulatekeeps running totals,pairwisepairs neighbours andbatchedchunks.groupbygroups only neighbouring items, so sort by the same key first.product,permutationsandcombinationslist every possibility; count first withmath.permandmath.comb.
Frequently asked questions
Do I need to install itertools?
No. It's part of Python's standard library, so import itertools works on any Python installation. pairwise needs Python 3.10 or newer and batched needs 3.12 or newer.
Is itertools faster than writing loops?
Usually, yes. The functions are written in C and avoid building intermediate lists, so they're fast and memory-friendly. The bigger benefit is clearer, shorter code.
What is the difference between itertools.product and nested loops?
They produce the same combinations in the same order. product is shorter, works for any number of groups without changing the code's shape, and is lazy.
What to learn next
- Work with functions as tools in Python functools: partial, reduce and lru_cache.
- Revise lazy data in Python generators and yield.
- See how counting choices leads into probability in the maths foundations course.