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.
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:
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))