Iterators, generators and itertools
How for really works, how to produce values on demand with generators, the complete itertools toolbox with the official recipes, and lazy pipelines that process large files in constant memory. Every runnable block is checked against its output.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| get an iterator from an iterable | iter(x) |
it = iter([1, 2]) |
| get the next value | next(it), next(it, default) |
next(it, None) never raises |
| get the first item that matches | next(gen, default) |
next((x for x in xs if x > 3), None) |
| produce values lazily | a generator function with yield |
def read_rows(path): ... yield row |
| write a one-line lazy sequence | generator expression | (x * x for x in xs) |
| delegate to another iterable | yield from it |
yield from flatten(child) |
| take the first n items | itertools.islice(it, n) |
list(islice(rows, 5)) |
| skip the first n items | islice(it, n, None) |
skip a header |
| process in chunks of n | itertools.batched(it, n) (3.12+) |
for batch in batched(rows, 1000): |
| loop over consecutive pairs | itertools.pairwise(it) |
for a, b in pairwise(xs): |
| make a sliding window | deque(maxlen=n) or the sliding_window recipe |
moving averages |
| chain several iterables | itertools.chain(a, b) |
chain(jan, feb, mar) |
| flatten one level | chain.from_iterable(nested) |
|
| count forever | itertools.count(start, step) |
ids |
| repeat a cycle | itertools.cycle(it) |
round-robin colors |
| running totals | itertools.accumulate(xs) |
accumulate(xs, max) for running max |
| group consecutive equal keys | itertools.groupby(sorted_it, key) |
sort by the same key first |
| take while a condition holds | takewhile(pred, it) / dropwhile(pred, it) |
sorted logs |
| filter with a mask | compress(data, selectors) |
|
| all pairs of two lists | itertools.product(a, b) |
grid search |
| all orderings / subsets of size k | permutations(it, k) / combinations(it, k) |
|
| zip to the longest input | zip_longest(a, b, fillvalue=...) |
|
| zip with equal lengths enforced | zip(a, b, strict=True) |
|
| call a function with unpacked tuples | itertools.starmap(f, pairs) |
starmap(pow, [(2, 3)]) |
| iterate twice over one iterator | itertools.tee(it, 2) (or a list) |
|
| call a function until a sentinel | iter(callable, sentinel) |
iter(lambda: f.read(4096), b"") |
| stream a big file line by line | for line in f: |
constant memory |
| count items of an iterator | sum(1 for _ in it) |
consumes it |
| make a class iterable | __iter__ that yields |
see iterator classes |
| type-hint a generator | Iterator[int] or Generator[int, None, None] (Generator[int] on 3.13+) |
from collections.abc import Iterator |
| peek without losing the item | first = next(it) then chain([first], it) |
Iterable, iterator, generator
Section titled “Iterable, iterator, generator”| Term | Has | Example | Reusable |
|---|---|---|---|
| iterable | __iter__() returning an iterator |
list, str, dict, range, file |
yes: each iter() starts fresh |
| iterator | __next__() and __iter__() returning itself |
iter([1, 2]), map(...), zip(...), file |
no: consumed once |
| generator | an iterator made by a yield function or (...) expression |
(x for x in xs) |
no |
| sequence | __getitem__ and __len__ |
list, tuple, str, range |
yes |
it = iter(["a", "b"]) # what `for` does firstprint(next(it), next(it), next(it, "done"))nums = [1, 2, 3]print(iter(nums) is iter(nums), iter(it) is it) # lists give new iterators
for_it = iter(nums) # a for loop, written out by handwhile True: try: item = next(for_it) except StopIteration: break print(item, end=" ")print()a b doneFalse True1 2 3| Built-in | Returns | Lazy |
|---|---|---|
range, dict.keys() / values() / items() |
a reusable view or sequence | yes, not one-shot |
map, filter, zip, enumerate, reversed |
an iterator | yes, one-shot |
open(...) |
a file object (an iterator over lines) | yes |
sorted, list, tuple |
a list or tuple | no: consumes everything |
sum, min, max, any, all, "".join |
one value | consumes (any / all stop early) |
Generator functions
Section titled “Generator functions”def countdown(n): print("start") # runs at the first next(), not at the call while n > 0: yield n # pause here and hand out n n -= 1 return "liftoff" # becomes StopIteration.value
gen = countdown(3)print(type(gen).__name__)print(next(gen), next(gen), next(gen))try: next(gen)except StopIteration as stop: print("finished:", stop.value)print(list(countdown(2)), list(gen)) # gen is exhaustedgeneratorstart3 2 1finished: liftoffstart[2, 1] []| Fact | Detail |
|---|---|
| calling a generator function | runs nothing; returns a generator object |
yield value |
pauses and hands out value; local state is kept |
return value |
ends the generator; for ignores the value |
raise StopIteration inside |
becomes a RuntimeError (PEP 479); use return |
gen.close() |
raises GeneratorExit at the paused yield; finally blocks run |
gen.send(x) |
resumes and makes yield evaluate to x (coroutine style; rare today) |
try / finally / with inside |
clean-up runs when the generator finishes or is closed |
Generator expressions vs list comprehensions
Section titled “Generator expressions vs list comprehensions”[f(x) for x in xs] |
(f(x) for x in xs) |
|
|---|---|---|
| result | a list in memory |
a generator |
| memory | O(n) | O(1) |
reuse, len, indexing |
yes | no |
| when work happens | at once | on each next() |
| use when | you need the values several times or need len |
you aggregate once: sum, max, any, writing to a file |
def noisy(x): print(f"compute {x}") return x * 10
lazy = (noisy(x) for x in range(5))print("nothing computed yet")print(next(lazy), next(lazy))print(any(noisy(x) > 15 for x in range(5))) # stops at the first Truenothing computed yetcompute 0compute 10 10compute 0compute 1compute 2Trueyield from
Section titled “yield from”def flatten(items): for item in items: if isinstance(item, (list, tuple)): yield from flatten(item) # delegate to the inner generator else: yield item
def read_all(*sources): for source in sources: yield from source # same as: for x in source: yield x
def inner(): yield 1 return "inner result"
def outer(): result = yield from inner() # receives inner's return value yield result
print(list(flatten([1, [2, (3, [4])], 5])), list(read_all("ab", [1, 2])), list(outer()))[1, 2, 3, 4, 5] ['a', 'b', 1, 2] [1, 'inner result']Iterator classes
Section titled “Iterator classes”Every iteration and container dunder (__iter__, __next__, __len__, __getitem__, __contains__) is in the dunder methods table.
class Countdown: """Iterable: each loop gets a fresh generator."""
def __init__(self, start): self.start = start
def __iter__(self): n = self.start while n > 0: yield n n -= 1
class Fib: """Iterator: one-shot, keeps its own state."""
def __init__(self, limit): self.a, self.b, self.limit = 0, 1, limit
def __iter__(self): return self
def __next__(self): if self.a > self.limit: raise StopIteration value = self.a self.a, self.b = self.b, self.a + self.b return value
c = Countdown(3)print(list(c), list(c), list(Fib(30)))[3, 2, 1] [3, 2, 1] [0, 1, 1, 2, 3, 5, 8, 13, 21]itertools
Section titled “itertools”Infinite iterators
Section titled “Infinite iterators”| Function | Yields | Example | Result |
|---|---|---|---|
count(start=0, step=1) |
start, start + step, … | islice(count(10, 5), 3) |
10 15 20 |
cycle(it) |
the items again and again | islice(cycle("ab"), 5) |
a b a b a |
repeat(x, n) |
x n times (forever without n) |
repeat(0, 3) |
0 0 0 |
Terminating iterators
Section titled “Terminating iterators”| Function | Yields | Example | Result |
|---|---|---|---|
accumulate(it, func=add, initial=None) |
running results | accumulate([1, 2, 3, 4]) |
1 3 6 10 |
batched(it, n) (3.12+) |
tuples of up to n items | batched("abcde", 2) |
('a','b') ('c','d') ('e',) |
chain(*its) |
items of each iterable in turn | chain("ab", [1]) |
a b 1 |
chain.from_iterable(its) |
same, from one iterable of iterables | chain.from_iterable([[1], [2, 3]]) |
1 2 3 |
compress(data, selectors) |
items whose selector is truthy | compress("abcd", [1, 0, 1, 0]) |
a c |
dropwhile(pred, it) |
everything after pred is first false |
dropwhile(lambda x: x < 3, [1, 4, 1]) |
4 1 |
takewhile(pred, it) |
items until pred is first false |
takewhile(lambda x: x < 3, [1, 4, 1]) |
1 |
filterfalse(pred, it) |
items where pred is false |
filterfalse(str.isdigit, "a1b2") |
a b |
groupby(it, key=None) |
(key, group) for each run of equal keys |
groupby("aabca") |
a b c a (keys) |
islice(it, stop) / islice(it, start, stop, step) |
a slice of any iterator | islice("abcdef", 1, None, 2) |
b d f |
pairwise(it) (3.10+) |
overlapping pairs | pairwise([1, 2, 3]) |
(1, 2) (2, 3) |
starmap(func, it) |
func(*item) |
starmap(pow, [(2, 3), (3, 2)]) |
8 9 |
tee(it, n=2) |
n independent iterators | a, b = tee(it) |
buffers what one has seen and the other has not |
zip_longest(*its, fillvalue=None) |
tuples until the longest ends | zip_longest("ab", "x", fillvalue="-") |
('a','x') ('b','-') |
Combinatoric iterators
Section titled “Combinatoric iterators”| Function | Yields | "ABC", k = 2 |
Count |
|---|---|---|---|
product(*its, repeat=1) |
the Cartesian product | AA AB AC BA BB BC CA CB CC (with repeat=2) |
n^k |
permutations(it, k) |
ordered arrangements, no repeats | AB AC BA BC CA CB |
n! / (n − k)! |
combinations(it, k) |
unordered subsets, no repeats | AB AC BC |
n! / (k! (n − k)!) |
combinations_with_replacement(it, k) |
unordered, with repeats | AA AB AC BB BC CC |
(n + k − 1)! / (k! (n − 1)!) |
import operatorfrom itertools import (accumulate, batched, chain, combinations, compress, count, cycle, groupby, islice, pairwise, permutations, product, starmap, takewhile, zip_longest)
print(list(islice(count(10, 5), 3)), list(islice(cycle("ab"), 5)))print(list(accumulate([3, 1, 4, 1, 5])), list(accumulate([3, 1, 4, 1, 5], max)))print(list(accumulate([1, 2, 3, 4], operator.mul, initial=10)))print(list(batched(range(7), 3)), list(pairwise("abcd")))print(list(chain("ab", [1, 2])), list(chain.from_iterable([[1], [2, 3]])))print(list(compress("abcd", [1, 0, 1, 0])), list(takewhile(lambda x: x < 5, [1, 4, 6])))print(list(starmap(pow, [(2, 3), (3, 2)])), list(zip_longest("ab", "x", fillvalue="-")))print(["".join(p) for p in product("AB", repeat=2)], len(list(permutations("ABCD", 2))))print(["".join(c) for c in combinations("ABCD", 2)])[10, 15, 20] ['a', 'b', 'a', 'b', 'a'][3, 4, 8, 9, 14] [3, 3, 4, 4, 5][10, 10, 20, 60, 240][(0, 1, 2), (3, 4, 5), (6,)] [('a', 'b'), ('b', 'c'), ('c', 'd')]['a', 'b', 1, 2] [1, 2, 3]['a', 'c'] [1, 4][8, 9] [('a', 'x'), ('b', '-')]['AA', 'AB', 'BA', 'BB'] 12['AB', 'AC', 'AD', 'BC', 'BD', 'CD']groupby
Section titled “groupby”from itertools import groupbyfrom operator import itemgetter
sales = [("North", 120), ("South", 80), ("North", 50), ("South", 30), ("East", 10)]unsorted = [(region, len(list(g))) for region, g in groupby(sales, key=itemgetter(0))]print(unsorted) # runs of equal keys onlyby_region = sorted(sales, key=itemgetter(0)) # sort by the same key firstfor region, group in groupby(by_region, key=itemgetter(0)): print(region, sum(amount for _, amount in group))print([(k, len(list(g))) for k, g in groupby("aaabccaa")]) # run-length encoding[('North', 1), ('South', 1), ('North', 1), ('South', 1), ('East', 1)]East 10North 170South 110[('a', 3), ('b', 1), ('c', 2), ('a', 2)]Recipes from the itertools docs
Section titled “Recipes from the itertools docs”from collections import dequefrom itertools import chain, islice, repeat, filterfalse, tee, zip_longest
def take(n, iterable): return list(islice(iterable, n))
def nth(iterable, n, default=None): return next(islice(iterable, n, None), default)
def first_true(iterable, default=None, pred=None): return next(filter(pred, iterable), default)
def sliding_window(iterable, n): it = iter(iterable) window = deque(islice(it, n - 1), maxlen=n) for x in it: window.append(x) yield tuple(window)
def unique_everseen(iterable, key=None): seen = set() for element in iterable: k = element if key is None else key(element) if k not in seen: seen.add(k) yield element
def partition(pred, iterable): t1, t2 = tee(iterable) return list(filterfalse(pred, t1)), list(filter(pred, t2))
def roundrobin(*iterables): sentinel = object() for group in zip_longest(*iterables, fillvalue=sentinel): yield from (x for x in group if x is not sentinel)
def padnone(iterable): return chain(iterable, repeat(None))
print(take(3, "abcdef"), nth("abcdef", 2), first_true([0, "", 7, 8]))print(list(sliding_window([1, 2, 3, 4, 5], 3)))print(list(unique_everseen("AaBbCcA", key=str.lower)), partition(str.isdigit, "a1b2"))print(list(roundrobin("ABC", "D", "EF")), take(4, padnone([1, 2])))['a', 'b', 'c'] c 7[(1, 2, 3), (2, 3, 4), (3, 4, 5)]['A', 'B', 'C'] (['a', 'b'], ['1', '2'])['A', 'D', 'E', 'B', 'F', 'C'] [1, 2, None, None]| Recipe | Does | Also in |
|---|---|---|
take(n, it) |
first n items as a list | more_itertools.take |
nth(it, n) |
item n or a default | |
first_true(it, default, pred) |
first truthy (or matching) item | |
sliding_window(it, n) |
overlapping windows of size n | more_itertools.windowed |
unique_everseen(it, key) |
dedupe, keep order, works on streams | |
partition(pred, it) |
split into false and true items | |
roundrobin(*its) |
interleave iterables | |
batched(it, n) |
chunks | built in since 3.12; strict=True in 3.13 |
flatten(list_of_lists) |
one level | chain.from_iterable |
Lazy pipelines
Section titled “Lazy pipelines”Each stage takes an iterator and yields items. Nothing runs until the last stage pulls values, and memory stays constant whatever the file size.
from collections import Counterfrom collections.abc import Iterable, Iterator
type Record = dict[str, str] # type alias statement (3.12+)
def read_lines(path: str) -> Iterator[str]: with open(path, encoding="utf-8") as f: for line in f: yield line.rstrip("\n")
def parse(lines: Iterable[str]) -> Iterator[Record]: for line in lines: parts = line.split(maxsplit=4) if len(parts) == 5 and parts[2] in {"INFO", "WARNING", "ERROR", "DEBUG"}: yield {"level": parts[2], "source": parts[3], "message": parts[4]}
def only(records: Iterable[Record], *levels: str) -> Iterator[Record]: return (r for r in records if r["level"] in levels)
problems = only(parse(read_lines("data/logs/app.log")), "WARNING", "ERROR")print(Counter(r["level"] for r in problems))first_error = next(only(parse(read_lines("data/logs/app.log")), "ERROR"), None)print(first_error["source"], first_error["message"][:60])Counter({'WARNING': 25, 'ERROR': 7})[db] OperationalError: database is locked (attempt 1/3), retryingimport csvfrom itertools import batched, islice
def revenue_rows(path): with open(path, newline="", encoding="utf-8") as f: for row in csv.DictReader(f): yield row["category"], float(row["revenue"])
totals = {}for batch in batched(revenue_rows("data/sales.csv"), 5000): # 5,000 rows at a time for category, revenue in batch: totals[category] = totals.get(category, 0) + revenuefor category, total in sorted(totals.items()): print(f"{category:<12}{total:>14,.2f}")print(list(islice(revenue_rows("data/sales.csv"), 2)))Beauty 150,417.76Books 106,908.12Clothing 314,686.62Electronics 1,808,108.17Home 672,294.61Sports 544,108.55[('Home', 66.49), ('Clothing', 14.99)]| Stage | Pattern |
|---|---|
| source | with open(...) inside a generator; yields lines or rows |
| transform | generator function or expression: parse, clean, enrich |
| filter | (r for r in rows if ...), filter, takewhile, dropwhile |
| limit | islice(rows, n) while you develop |
| group | batched for chunks; groupby on sorted input |
| sink | sum, Counter, max, a for loop that writes, csv.writer.writerows |
Type hints for iterators
Section titled “Type hints for iterators”| Hint | Use |
|---|---|
Iterable[T] |
parameters: anything you can loop over |
Iterator[T] |
return type of most generator functions |
Generator[Y, S, R] |
when you use send or the return value; Generator[int, None, None] (Generator[int] on 3.13+) |
AsyncIterator[T] |
async def with yield |
| import from | collections.abc (not typing) |
Gotchas
Section titled “Gotchas”| Trap | Symptom | Fix |
|---|---|---|
| iterating an iterator twice | the second loop is empty | make a list, or call the generator function again |
x in iterator |
consumes items up to the match | use a list or set for membership |
len(gen) |
TypeError: object of type 'generator' has no len() |
sum(1 for _ in gen) or a list |
gen[0] |
TypeError: 'generator' object is not subscriptable |
next(gen) or islice |
| printing a generator | <generator object ...> |
list(gen) for small ones |
groupby on unsorted data |
the same key appears in several groups | sorted(data, key=k) first |
keeping a groupby group for later |
it is empty after the next group | list(group) at once |
tee then using the original |
the tees miss items | use only the tees |
tee with one copy far ahead |
memory grows | use a list |
raise StopIteration in a generator |
RuntimeError: generator raised StopIteration |
return |
next(gen) on an empty generator |
StopIteration escapes |
next(gen, default) |
a generator over an open file returned from with |
ValueError: I/O operation on closed file |
open the file inside the generator |
a generator expression’s first for |
evaluated at once; the rest are lazy | build it where the data is ready |
zip(it, it) |
pairs consecutive items (a trick, not a bug) | use batched(it, 2) for clarity |
zip on unequal lengths |
silent truncation | zip(..., strict=True) or zip_longest |
map with a lambda per item |
slower and less readable | a generator expression |
| side effects in a generator | they run only when consumed, maybe never | consume with a loop, or do the work eagerly |
Learn more
Section titled “Learn more”- 10. Iterators and generators and its cheat sheet
- 09. Standard library for
itertoolsandcollections - Collections and comprehensions
- Files, paths and formats for streaming files
- OOP sheet: dunder methods: containers and iteration