itertools provides iterator-building tools for combining, selecting, grouping and accumulating values.
Compose operations on streams and understand when adjacency or a shared cursor changes the result.
Iterator tools can combine sources, enumerate combinations, and group adjacent
records without building every output first. Their storage and consumption
rules differ. Follow chain, product, groupby, and islice at the points
where they pull input, retain it, or discard it; those boundaries explain most
surprising results when the tools are composed.

Combine two menus into one listing
A breakfast menu and a lunch menu need to print as one combined list. + only
works when both sides are the same concrete type — it breaks the moment one side is
a generator instead of a list:
breakfast = ["idli", "dosa"]
lunch = (item for item in ["rice", "dal"]) # a generator, not a list
print(breakfast + lunch)chain walks any iterables end to end, lazily — it never builds the combined
sequence in memory before you start reading it:
Preparing this topic’s interactive investigation…
Every outfit combination
A shop wants every size/colour combination it stocks, to generate a page for each.
Nested loops do it, but product says the same thing in one line:
product also takes repeat= for combining one iterable with itself — every
sequence of n coin flips, say:
Group consecutive log levels
A log file's levels need collapsing into runs — how many INFO lines in a row,
before the next ERROR. groupby does exactly that, but only for neighbours:
from itertools import groupby
logs = ["INFO", "INFO", "ERROR", "INFO"]
groups = [key for key, _ in groupby(logs)]
print(groups)If you want every INFO merged into a single group regardless of where it sits,
sorted() first — groupby only ever sees what's already next to each other:
A group is a view onto a shared cursor
groupby does not hand you independent lists. Each group reads from the same
source cursor as the outer iterator. Advancing the outer iterator moves past
the previous run, so save that run's values while it is current if needed later.
This prints a [] then b ['b']: the first run was passed while finding the
second. A list of group iterators is therefore not a saved grouped dataset.
The earlier [(key, list(group)) ...] example materialises each group at the
right time. For counts, sum(1 for _ in group) consumes it without keeping all
its values.
Check what each tool retains before assuming “iterator” means no storage.
product caches its finite input pools, then produces combinations lazily;
it cannot accept an infinite input. tee buffers values when consumers advance
at different speeds. islice discards skipped values by consuming them and
does not support negative indices or a negative step.
For log compression, sorting first would destroy the original run boundaries.
Try sources ['a', 'b'] and ['b', 'a']: chaining before grouping should
produce runs a, b, a, merging the two adjacent boundary bs. Explain
why grouping each source independently would produce a different boundary.
One more: islice
A generator has no [5:10] — it isn't indexable. islice slices it anyway,
without turning it into a list first (which would defeat the point of a generator
that might never end):
Quick practice
from itertools import chain
a = [1, 2]
b = [3, 4]
combined = chain(a, b)
print(list(combined), list(combined))TypeErrorRun it and read the error. Fix the line so it actually counts the outcomes.
🎯 Your turn
Write menu_combinations(mains, sides): return every [main, side] pairing as a
list of two-item lists, using itertools.product.
menu_combinations(["dosa", "idli"], ["chutney", "sambar"])→[["dosa", "chutney"], ["dosa", "sambar"], ["idli", "chutney"], ["idli", "sambar"]]menu_combinations([], ["chutney"])→[]
Hint: product(mains, sides) yields (main, side) tuples — turn each into a
list: [list(pair) for pair in product(mains, sides)].
Press ▶ Run and hit ✓ Check. ✅
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write combine_menus(a, b) returning every item of a followed by every item of b, as one list, using itertools.chain.
Write all_outcomes(faces, rolls) returning every possible sequence of rolls rolls, each as a list, using itertools.product with repeat=rolls.
Write group_consecutive(items) returning [[key, [items...]], ...] for each run of consecutive equal items, using itertools.groupby. Do not sort — runs must stay in their original order.
Write first_multiples(n, step): using an infinite generator that yields 0, step, 2*step, ..., return the first n values as a list, using itertools.islice.
Write compress_log(sources): sources is a list of lists of log levels. Chain them all into one stream in order, then return just the keys of each consecutive run (drop the counts), using chain.from_iterable and groupby.