The itertools module is a toolbox of fast, memory-friendly building blocks for working with sequences. It can count forever, cycle through options, list every combination of a set, keep running totals, group sorted records and split data into batches. Because its functions return iterators, they produce one item at a time instead of building large lists. This lesson tours the most useful tools with practical examples.
In this lesson you will learn
- Infinite iterators:
count,cycleandrepeat - Combinatorics:
combinations,permutationsandproduct - Running totals with
accumulate, joining withchain - Grouping with
groupbyand filtering withtakewhileanddropwhile pairwise,batchedandzip_longest
You should know iterators and generators and built-in functions.
Infinite Iterators, Combinatorics and Accumulate
import itertools as it
# Infinite iterators: always limit them with islice or a break
print(list(it.islice(it.count(start=10, step=5), 4)))
print(list(it.islice(it.cycle(["red", "green"]), 5)))
print(list(it.repeat("hi", 3)))
# Combinatorics
teams = ["Dhaka", "Khulna", "Sylhet"]
print(list(it.combinations(teams, 2))) # matches, order does not matter
print(len(list(it.permutations(teams, 2)))) # home and away, order matters
print(list(it.product("AB", [1, 2]))) # every pairing
print(list(it.combinations_with_replacement("xy", 2)))
# Running totals and joining iterables
sales = [1200, 450, 800, 2300]
print(list(it.accumulate(sales)))
print(list(it.accumulate(sales, max)))
print(list(it.chain([1, 2], (3, 4), "ab")))
Output
[10, 15, 20, 25]
['red', 'green', 'red', 'green', 'red']
['hi', 'hi', 'hi']
[('Dhaka', 'Khulna'), ('Dhaka', 'Sylhet'), ('Khulna', 'Sylhet')]
6
[('A', 1), ('A', 2), ('B', 1), ('B', 2)]
[('x', 'x'), ('x', 'y'), ('y', 'y')]
[1200, 1650, 2450, 4750]
[1200, 1200, 1200, 2300]
[1, 2, 3, 4, 'a', 'b']
count(10, 5)counts 10, 15, 20, … forever, andcyclerepeats a sequence forever.islicetakes just the first few items, like slicing a list.combinations(teams, 2)lists every pair where order does not matter: three teams give three matches.permutationscounts (Dhaka, Khulna) and (Khulna, Dhaka) separately, giving 6.productgives every pairing of items from several inputs, like nestedforloops.combinations_with_replacementallows an item to pair with itself.accumulateproduces running totals: the sales so far after each day. Givenmax, it gives the running maximum instead.chainjoins several iterables into one stream without building a new list.
Grouping, Filtering and Windows
import itertools as it
orders = [("2026-01", "Karim", 1200), ("2026-01", "Rina", 450),
("2026-02", "Joya", 2300), ("2026-02", "Rina", 650), ("2026-03", "Karim", 1500)]
# groupby groups *consecutive* items with the same key (sort first!)
for month, group in it.groupby(orders, key=lambda o: o[0]):
group = list(group)
print(f"{month}: {len(group)} order(s), {sum(o[2] for o in group)} taka")
# takewhile / dropwhile stop or start at the first failing item
temps = [24, 27, 31, 35, 29, 22]
print(list(it.takewhile(lambda t: t < 33, temps)), list(it.dropwhile(lambda t: t < 33, temps)))
# compress keeps items where the selector is truthy
print(list(it.compress(["a", "b", "c", "d"], [1, 0, 1, 0])))
# pairwise and batched (Python 3.10+ and 3.12+)
print(list(it.pairwise([10, 13, 9, 15])))
print([b - a for a, b in it.pairwise([10, 13, 9, 15])])
print(list(it.batched(range(1, 8), 3)))
# zip_longest fills in for the shorter input
print(list(it.zip_longest("abc", [1, 2], fillvalue="-")))
Output
2026-01: 2 order(s), 1650 taka
2026-02: 2 order(s), 2950 taka
2026-03: 1 order(s), 1500 taka
[24, 27, 31] [35, 29, 22]
['a', 'c']
[(10, 13), (13, 9), (9, 15)]
[3, -4, 6]
[(1, 2, 3), (4, 5, 6), (7,)]
[('a', 1), ('b', 2), ('c', '-')]
groupbygroups consecutive items that share a key. The orders were already in month order, so each month formed one group. With unsorted data, sort by the same key first or a key can appear in several groups.- Each group is itself an iterator, so
list(group)stores it before it is used twice (for counting and summing). takewhilekeeps items until the condition first fails;dropwhileskips items until then. Neither looks at the condition again after that point, which is why 29 and 22 follow 35.compresskeeps the items whose selector is truthy.pairwiseyields overlapping neighbours, ideal for day-to-day changes.batched(Python 3.12+) splits data into chunks of a fixed size, with a shorter final chunk.zip_longestkeeps going until the longest input ends, filling the gaps withfillvalue.
itertools Cheat Sheet
| Function | Example | Result |
|---|---|---|
count(start, step) | count(1, 2) | 1, 3, 5, … |
cycle(it) | cycle("AB") | A, B, A, B, … |
islice(it, n) | islice(count(), 3) | 0, 1, 2 |
combinations(it, r) | combinations("ABC", 2) | AB, AC, BC |
permutations(it, r) | permutations("AB") | AB, BA |
product(a, b) | product("AB", "12") | A1, A2, B1, B2 |
accumulate(it) | accumulate([1, 2, 3]) | 1, 3, 6 |
chain(a, b) | chain([1], [2, 3]) | 1, 2, 3 |
groupby(it, key) | groupby("aabbb") | a: aa, b: bbb |
pairwise(it) | pairwise([1, 2, 3]) | (1, 2), (2, 3) |
batched(it, n) | batched("ABCDE", 2) | AB, CD, E |
Common Mistakes
- Calling
list()on an infinite iterator such ascount(); the program never finishes. Limit it withisliceor abreak. - Using
groupbyon unsorted data and getting the same key in several groups. - Reading an iterator twice. Like all iterators, itertools results are used up after one pass.
- Generating huge combinations.
permutationsof 12 items already gives about 479 million results.
Practice Exercises
Exercise 1. List every possible 3-character PIN using only the digits 1, 2 and 3. How many are there?
Show answer
import itertools as it
pins = ["".join(p) for p in it.product("123", repeat=3)]
print(len(pins), pins[:4]) # 27 ['111', '112', '113', '121']
Exercise 2. Count how many times each letter appears in a row in "aaabccdddd", producing [('a', 3), ('b', 1), ('c', 2), ('d', 4)].
Show answer
import itertools as it
print([(ch, len(list(g))) for ch, g in it.groupby("aaabccdddd")])
This is run-length encoding, a simple compression method.
Frequently Asked Questions
Why use itertools instead of writing loops?
The functions are written in C, so they are fast, and they produce items lazily, so they use very little memory even for long or endless sequences. They also make the intent of the code clearer.
What if I have an older Python without batched?
batched arrived in Python 3.12 and pairwise in 3.10. On older versions, the official itertools documentation lists short recipes that do the same job.
Summary
- itertools functions return lazy iterators that save memory.
- Limit infinite iterators with
islice. combinations,permutationsandproductgenerate every arrangement.- Sort before
groupby; useaccumulate,pairwiseandbatchedfor running totals, neighbours and chunks.
Next: Python CSV Files.
