Mastery
Mastery/Python/B. Iteration & generators
T2 · intermediate depth

itertools deep-dive

Lazy, composable iterator building blocks that avoid materializing intermediate lists. The one genuine trap: groupby only groups consecutive runs of a matching key -- it does NOT scan the whole iterable for all matching items the way a groupBy in other languages might imply. Forgetting to sort first is one of the most common itertools mistakes.

python
import itertools

print("islice (lazy slicing, works on infinite iterators too):", list(itertools.islice(range(100), 5, 10)))

a, b = itertools.tee([1, 2, 3], 2)   # split one iterator into N independent ones
print("tee gives independent iterators:", list(a), list(b))

print("chain:", list(itertools.chain([1, 2], [3, 4])))
print("accumulate (running total):", list(itertools.accumulate([1, 2, 3, 4])))
print("pairwise (consecutive pairs):", list(itertools.pairwise([1, 2, 3, 4])))

The groupby trap, side by side -- same data, only the sorting differs:

python
data = [("a", 1), ("a", 2), ("b", 3), ("a", 4)]

print("groupby WITHOUT sorting first (wrong -- groups only consecutive runs):")
for k, g in itertools.groupby(data, key=lambda x: x[0]):
    print(" ", k, list(g))

print("groupby WITH sorting first (correct -- all matching items grouped together):")
for k, g in itertools.groupby(sorted(data), key=lambda x: x[0]):
    print(" ", k, list(g))

Interview angle

Interviewers use itertools familiarity as a quick "how much Python have you actually written" signal — candidates who hand-roll a manual running-total loop instead of reaching for accumulate, or who don't know groupby needs sorted input, are showing a gap that's easy to spot and easy to teach. The groupby sorting trap specifically makes a great live-coding gotcha question since the bug is silent, not a crash.

In the industry

itertools functions are preferred over hand-rolled loops specifically because they're lazy (memory- efficient on large data) and because reviewers immediately recognize the intent (pairwise, accumulate) versus having to read a custom loop to figure out what it's doing. The groupby-without-sorting bug is common enough in real code that "did you sort first?" is a standard code-review question the moment groupby appears in a diff.