Lesson · Iteration Protocol
itertools
61 min readitertools
`itertools` provides efficient iterator building blocks for infinite streams, slicing, chaining, grouping, products, permutations, and combinations. The power comes from composing lazy operations.
Learning goals
- Choose the right itertool for a job: counting without a loop counter, chaining sources, capping an infinite stream, or building combination math.
- Explain why
count()andcycle()never end and howislice()orzip()makes them safe to consume. - Predict the tuples
product(["S", "M"], ["red", "blue"])yields, in order. - Use
permutationsandcombinationsand state the difference between ordered and unordered selections. - Explain the sorting rule that makes
groupbyproduce the groups you expect.
Mental model
The tools split into two families: producers of infinite or repeated values (count, cycle, repeat) and transforms that consume finite inputs (chain, islice, product, permutations, combinations, groupby). Everything returns a lazy iterator, so list() or a for loop is what actually drives it, and an infinite source only becomes safe once something downstream stops asking for values.
Mental model
read it top to bottom
endless streams count, cycle, repeat bound or slice them islice join sources chain combination math product, permutations, combinations runs of equal keys groupby (sort by key first)
Core idea
itertools is a composition kit rather than a set of algorithms: each function returns a lazy iterator, so the output of one feeds straight into the next and nothing runs until a consumer pulls. The family splits into producers of endless streams (count, cycle, repeat) and finite transforms (chain, islice, product, permutations, combinations, groupby). Two classic traps follow from that design: an unbounded producer must be capped by a consumer, and position-based tools (groupby most of all) must receive input prepared in the order they assume.
count
count(start, step) yields evenly spaced numbers forever, beginning at start and adding step on each request; both may be floats. It is an infinite iterator, so it is normally paired with islice, zip, or a break to bound it.
cycle
cycle(iterable) yields every element of the input and then starts over from the beginning, forever. It saves the elements as it goes, so cycling a large input costs memory proportional to that input.
repeat
repeat(value, times) yields the same value over and over, times times, or forever when times is omitted. The values are produced on demand, so no list of copies is ever built.
chain
chain(*iterables) walks the inputs one after another, yielding every element of the first, then every element of the second, and so on. It is lazy, so later iterables are not touched until the earlier ones are exhausted.
islice
islice(iterable, stop) or islice(iterable, start, stop, step) yields the selected slice of an iterator without copying it. stop may be None for an open-ended slice, and negative positions are not supported.
product
product(*iterables, repeat=1) yields the Cartesian product as tuples, like nested for loops over the inputs. It reads each input into an internal pool first, so the inputs must be finite.
permutations
permutations(iterable, r=None) yields every ordered arrangement of r elements chosen from the input, with no position reused inside one arrangement. Elements are taken by position, so equal values from different positions still count as distinct arrangements.
combinations
combinations(iterable, r) yields every unordered selection of r elements: order inside a tuple does not matter and each selection appears once. Inputs are treated by position, and equal values from different positions can still produce separate tuples.
groupby
groupby(iterable, key=None) yields (key, group) pairs, starting a new group every time the key changes. It only groups adjacent items, so sort the input by the same key first when equal keys should land in one group.
Walkthrough
numbers = chain([1, 2], [3, 4])builds a lazy iterator, so no combined list exists yet;list(numbers)drives it through both inputs and prints[1, 2, 3, 4].islice(range(100), 5, 10)copies nothing: it skips five values, then yields the next five, so the result is[5, 6, 7, 8, 9].product(["S", "M"], ["red", "blue"])pairs every size with every color in the given order, producing[("S", "red"), ("S", "blue"), ("M", "red"), ("M", "blue")]once wrapped inlist.- Predict before running: all three printed lines, and whether
numbersproduces anything on a second pass.
Experiments to try
- Consume
chain([1, 2], [3, 4])twice, first withlistand then withsum, and explain the second result. - Replace
islicewith slicing (range(100)[5:10]) and state which form still works when the source is an iterator rather than a sequence. - Swap the two arguments of
productand compare the tuple order; then addrepeat=2and count the results. - Feed
groupbyan unsorted list of letters, then the sorted version, and compare how many groups each run produces.
Common mistakes
- Treating an itertool's return value as a collection:
count(),chain(...), andproduct(...)hand back iterators, solen()and indexing raiseTypeErrorand a second pass yields nothing. - Letting an infinite producer run:
list(count())orlist(cycle("AB"))keeps asking forever, so cap the stream withisliceorzipbefore consuming it. - Expecting
groupbyto gather all equal keys: it starts a new group every time the key changes, so equal keys that are not adjacent end up in separate groups; sort by the same key first. - Forgetting that combination tools work by position:
permutationsandcombinationstreat equal values from different positions as distinct, so deduplicate the results with a set when needed.
Practice: Easy
- Run the three worked example lines and record every printed value; then call
list(numbers)a second time and explain the empty result. - Use
islice(count(10), 4)to produce[10, 11, 12, 13]; state whylist(count(10))is not a safe substitute. - Build
list(zip(cycle("AB"), range(5)))and predict the five pairs before running.
Practice: Medium
- Chain three inputs (a list, a range, and a tuple) with
chainand print the result; then repeat withchain.from_iterableon a list of the three inputs. - Use
repeat("x", 3)insidezipto pair it with three names; explain what changes when thetimesargument is omitted and whyzipstill stops. - Produce all 2-item permutations and combinations of
["a", "b", "c"]; count each result and explain why the permutation list is longer.
Practice: Hard
- Build a report pipeline from
countfor row numbers andisliceto cap at five rows, plus a stage that formats each pair; state exactly which stage would hang without the cap. - Sort a list of words by length and run
groupbyto print one group per length; then run it on the unsorted list and account for every group difference. - Use
product("HT", repeat=3)to generate all eight coin-flip outcomes; then count how many contain exactly two heads with a comprehension over the product, keeping generation and counting as separate stages.
Lesson checklist
- I can pick the right tool for endless streams, slicing, chaining, and combination math.
- I can explain why
list(count())is dangerous and howisliceorzipcaps an infinite source. - I can predict the order and count of
product,permutations, andcombinationsresults. - I can prepare input for
groupbyso each key produces one group.
Remember
`itertools` supplies lazy building blocks: `count`, `cycle`, and `repeat` produce streams without end, while `chain`, `islice`, `product`, `permutations`, `combinations`, and `groupby` transform finite inputs. Composition is the point, so one tool's iterator feeds the next and nothing runs until a consumer pulls. Cap infinite producers, and sort before `groupby`, because both tools do exactly what their contracts say and nothing more.
Interview angles
What is the main purpose of **count**?+
count(start, step) yields evenly spaced numbers forever, beginning at start and adding step on each request. It is an infinite iterator, so it is normally paired with islice, zip, or a break to bound it.
What should you pay attention to when using **cycle**?+
cycle(iterable) yields every element of the input and then starts over, forever. It saves the elements as it goes, so cycling a large input costs memory proportional to that input.
How does **repeat** fit into this lesson?+
repeat(value, times) yields the same value over and over, times times, or forever when times is omitted. The values are produced on demand, so no list of copies is ever built.
Why does `groupby` need sorted input to gather equal keys into one group?+
groupby starts a new group at every key change, so it only collects runs of equal keys that sit next to each other. Sorting by the same key first lines up the equal keys, and only then does each key map to a single group.