10. Iterators and generators — Cheat sheet
The essentials of module 10 on one page. Every runnable block on this page is checked against its output. The blocks run top to bottom, so later blocks reuse earlier imports and functions.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| get an iterator from an iterable | iter(x) |
it = iter(["S1", "S2"]) |
| take the next item | next(it) |
next(it) → 'S1' |
| take the next item, or a default at the end | next(it, default) |
next(it, None) |
| check if an object is a one-pass iterator | iter(x) is x |
iter(f) is f → True for a file |
| write a lazy function | yield in a def |
def rows(): yield ... |
| yield every item of another iterable | yield from it |
yield from csv.DictReader(f) |
| build a lazy one-liner | generator expression | (float(t) for t in raw) |
| sum, count, test without a list | genexp as the only argument | sum(1 for r in rows if r["status"] != "ok") |
| stop at the first match | any(), next() on a genexp |
next((r for r in rows if hot(r)), None) |
| see the first n items of a stream | islice(it, n) |
list(islice(rows, 5)) |
| skip n items, then continue | islice(it, n, None) |
islice(rows, 6000, None) |
| process in chunks of n | itertools.batched(it, n) (3.12+) |
for chunk in batched(rows, 5_000): |
| start a sorted stream at a key | dropwhile(pred, it) |
dropwhile(lambda r: r["order_date"] < "2024-01-01", rows) |
| stop a sorted stream at a key | takewhile(pred, it) |
takewhile(lambda r: r["order_date"] <= end, rows) |
| join several streams | chain(a, b), chain.from_iterable(its) |
chain.from_iterable(read_rows(p) for p in paths) |
| group consecutive equal keys | groupby(it, key) |
groupby(rows, key=lambda r: r["order_date"]) |
| get running totals | accumulate(it) |
accumulate(daily_revenue) |
| compare each item with the next | pairwise(it) |
for a, b in pairwise(temps): |
| keep the last n items | deque(it, maxlen=n) |
deque(read_lines(p), maxlen=10) (a tail) |
| keep the top n of a stream | heapq.nlargest(n, it, key=...) |
nlargest(5, orders) |
| reuse a stream twice | re-create it, a re-iterable class, or list() if small |
SensorColumn(path, col) |
| close a paused generator now | gen.close() |
runs its finally and with cleanup |
| inspect a generator’s state | inspect.getgeneratorstate(gen) |
'GEN_SUSPENDED' |
| stream a CSV with pandas | pd.read_csv(path, chunksize=n) |
for chunk in reader: ... |
| measure peak memory | tracemalloc |
tracemalloc.get_traced_memory() |
Iterable, iterator, generator
Section titled “Iterable, iterator, generator”| Term | Has | Passes | Examples |
|---|---|---|---|
| iterable | __iter__ (returns an iterator) |
many if it makes a fresh iterator each time | list, str, dict, range, a re-iterable class |
| iterator | __next__ and __iter__ returning self |
one | file, csv.reader, map, zip, enumerate, generators |
| generator | made by a function with yield or by a genexp |
one | read_rows(path), (x * 2 for x in xs) |
import csvfrom collections.abc import Iterable, Iterator
statuses = ["ok", "warn", "fail"]it = iter(statuses) # a list_iteratorprint(next(it), next(it), next(it), next(it, "end")) # default instead of StopIterationprint(iter(statuses) is statuses, iter(it) is it) # list: no; iterator: yesok warn fail endFalse TrueWhat for x in iterable: does:
it = iter(iterable)while True: try: x = next(it) except StopIteration: break ... # loop bodyThree ways to make values on demand
Section titled “Three ways to make values on demand”from datetime import date, timedeltafrom typing import Self
class DayIterator: # 1. iterator class: one pass def __init__(self, start: date, end: date) -> None: self.current, self.end = start, end
def __iter__(self) -> Self: return self
def __next__(self) -> date: if self.current > self.end: raise StopIteration day, self.current = self.current, self.current + timedelta(days=1) return day
def days(start: date, end: date) -> Iterator[date]: # 2. generator: one pass while start <= end: yield start start += timedelta(days=1)
class DaySpan: # 3. re-iterable class: fresh generator per loop def __init__(self, start: date, end: date) -> None: self.start, self.end = start, end
def __iter__(self) -> Iterator[date]: return days(self.start, self.end)
week = (date(2024, 7, 14), date(2024, 7, 20))one_pass, span = DayIterator(*week), DaySpan(*week)print(len(list(one_pass)), len(list(one_pass))) # second pass is emptyprint(len(list(span)), len(list(span))) # every pass is fullprint(sum(1 for _ in days(*week)))7 07 77| Choose | When |
|---|---|
| generator function | the default: lazy values with any logic, a few lines |
| generator expression | one map and/or filter expression, consumed once |
| re-iterable class | callers loop several times over a big source (each loop re-reads it) |
| iterator class | the iterator needs extra methods or public state; rare |
Generator behavior
Section titled “Generator behavior”| Fact | Detail |
|---|---|
| calling the function runs nothing | it returns a generator in state GEN_CREATED |
next() runs to the next yield |
then the generator is GEN_SUSPENDED, with its local variables kept |
the body ends or hits return |
StopIteration is raised for you; state GEN_CLOSED |
return value |
the value is stored on StopIteration.value; yield from returns it |
raise StopIteration inside |
becomes RuntimeError (PEP 479): use return |
gen.close() |
raises GeneratorExit at the paused yield; finally and with run |
gen.send(x) |
resumes and makes the paused yield evaluate to x; rare in data code |
| type hint | Iterator[T] when callers only loop; Generator[T, None, None] when they call close(), send(), throw() or inspect it |
import inspectfrom collections.abc import Generator
def tagged(values: Iterable[float]) -> Generator[str, None, None]: try: for v in values: yield f"{v:.1f} °C" finally: print("cleanup") # runs at the end, or on close()
gen = tagged([20.21, 22.3, 19.4])print(inspect.getgeneratorstate(gen))print(next(gen), inspect.getgeneratorstate(gen))gen.close()print(inspect.getgeneratorstate(gen))GEN_CREATED20.2 °C GEN_SUSPENDEDcleanupGEN_CLOSEDGenerator expressions vs list comprehensions
Section titled “Generator expressions vs list comprehensions”[expr for x in it] |
(expr for x in it) |
|
|---|---|---|
| builds | a list, now | a generator, lazily |
| memory | grows with the data | constant (about 200 bytes) |
len(), [i], several passes |
yes | no |
| best for | small data you reuse, sorting, indexing | one pass into sum, max, any, join, a loop, a pipeline |
import sys
print(sys.getsizeof([n for n in range(100_000)]) > 100 * sys.getsizeof( n for n in range(100_000)))print(sum(n * n for n in range(4))) # no extra parentheses as the only argumentprint(sorted((n % 3 for n in range(6)), reverse=True)) # parentheses needed: 2 argsTrue14[2, 2, 1, 1, 0, 0]sys.getsizeof() measures only the outer object, not the items it refers to. Use tracemalloc to measure the real peak memory of a job.
Pipeline template
Section titled “Pipeline template”from collections import Counter, defaultdict, dequefrom itertools import batched, islice
def read_rows(path: str) -> Iterator[dict[str, str]]: # source with open(path, encoding="utf-8", newline="") as f: yield from csv.DictReader(f)
type Sale = tuple[str, str, float] # type alias (3.12+): date, category, revenue
def parse(rows: Iterable[dict[str, str]]) -> Iterator[Sale]: for r in rows: # transform: keep and type the needed columns yield r["order_date"], r["category"], float(r["revenue"])
def in_year(sales: Iterable[Sale], year: str) -> Iterator[Sale]: # filter return (s for s in sales if s[0].startswith(year))
totals: defaultdict[str, float] = defaultdict(float) # sinkfor _, category, revenue in in_year(parse(read_rows("data/sales.csv")), "2023"): totals[category] += revenueprint(max(totals, key=totals.get), f"{max(totals.values()):,.2f}")Electronics 868,183.40| Stage | Takes | Returns | Rule |
|---|---|---|---|
| source | a path, a connection, a URL | iterator of raw items | open the resource inside the generator |
| transform | iterator | iterator | one item in, zero or one item out |
| pass-through | iterator + a counter | the same items | count or log on the way, change nothing |
| sink | iterator | a result | the only loop that drives the pipeline |
Chunks
Section titled “Chunks”print([len(c) for c in batched(read_rows("data/sales.csv"), 5_000)])
def chunked(iterable: Iterable[str], n: int) -> Iterator[list[str]]: it = iter(iterable) # one shared position: required for lists while chunk := list(islice(it, n)): yield chunk
print(list(chunked("ABCDEFG", 3)))[5000, 5000, 5000, 5000, 228][['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]| Tool | Yields | Notes |
|---|---|---|
batched(it, n) |
tuples of up to n |
Python 3.12+; strict=True (3.13+) rejects a short last batch |
chunked recipe above |
lists of up to n |
works on any version; call iter() first |
pd.read_csv(path, chunksize=n) |
DataFrames of n rows |
use it as a context manager: with pd.read_csv(...) as reader: |
con.executemany(sql, chunk) |
— | the typical sink for a chunk: one call per batch |
itertools for streams
Section titled “itertools for streams”| Function | Example | Result |
|---|---|---|
islice(it, stop) |
islice("ABCDEFG", 3) |
A B C |
islice(it, start, stop, step) |
islice("ABCDEFG", 1, 6, 2) |
B D F |
takewhile(pred, it) |
takewhile(lambda x: x < 3, [1, 2, 3, 1]) |
1 2 |
dropwhile(pred, it) |
dropwhile(lambda x: x < 3, [1, 2, 3, 1]) |
3 1 |
chain(a, b) |
chain("AB", "CD") |
A B C D |
chain.from_iterable(its) |
chain.from_iterable(["AB", "CD"]) |
A B C D |
batched(it, n) |
batched("ABCDE", 2) |
('A','B') ('C','D') ('E',) |
groupby(it, key) |
groupby("AABBBA") |
A:2 B:3 A:1 (consecutive runs) |
accumulate(it) |
accumulate([5, 3, 2]) |
5 8 10 |
pairwise(it) |
pairwise([20.2, 20.4, 20.1]) |
(20.2, 20.4) (20.4, 20.1) |
tee(it, n) |
a, b = tee(it) |
two copies; buffers the gap between them |
count(start, step) |
count(1) |
1 2 3 … forever |
zip_longest(a, b, fillvalue=v) |
zip_longest("AB", "C", fillvalue="-") |
('A','C') ('B','-') |
compress(data, flags) |
compress("ABCD", [1, 0, 1, 0]) |
A C |
from itertools import accumulate, groupby, pairwise, takewhile, tee
print([(k, len(list(g))) for k, g in groupby("AABBBA")]) # runs, not totalsprint(list(accumulate([5, 3, 2])))print([round(b - a, 2) for a, b in pairwise([20.2, 20.4, 20.1])])print(list(takewhile(lambda x: x < 3, [1, 2, 3, 1])))src = iter([1, 2, 3, 4])a, b = tee(src)print(next(a), next(src), list(a), list(b)) # 2 went to src: both copies lose it[('A', 2), ('B', 3), ('A', 1)][5, 8, 10][0.2, -0.3][1, 2]1 2 [3, 4] [1, 3, 4]Recipes from the itertools docs
Section titled “Recipes from the itertools docs”A recipe is a small helper built from itertools. Copy it from the “Itertools Recipes” section of the Python docs, or install more-itertools, which ships them all.
| Recipe | Does | One-line version or core idea |
|---|---|---|
take(n, it) |
first n items as a list |
list(islice(it, n)) |
sliding_window(it, n) |
overlapping windows of n |
a deque(maxlen=n); yield tuple(window) after each append |
unique_everseen(it) |
distinct items, first-seen order | a seen set; memory grows with distinct items |
first_true(it, default, pred) |
first item where pred is true |
next(filter(pred, it), default) |
consume(it, n) |
advance n items |
next(islice(it, n, n), None) |
nth(it, n, default) |
the item at position n |
next(islice(it, n, None), default) |
partition(pred, it) |
false items, true items | tee + filterfalse and filter |
roundrobin(*its) |
one item from each in turn | cycle over the iterators, drop each one when it is exhausted |
from itertools import filterfalse
def nth[T](it: Iterable[T], n: int, default: T | None = None) -> T | None: return next(islice(it, n, None), default) # [T]: generic (3.12+)
rows = read_rows("data/sales.csv")row_100 = nth(rows, 99) # position 99 = data line 100print(row_100["order_id"] if row_100 else "file too short")print(list(filterfalse(lambda x: x % 2, range(6)))) # items where pred is falseO000074[0, 2, 4]Streaming sinks
Section titled “Streaming sinks”| Result | Sink | Memory |
|---|---|---|
| total, count, mean | one loop with accumulators, or sum(), statistics.fmean() |
constant |
| min, max | min(), max(), or max(..., key=...) |
constant |
| counts per key | Counter(r["k"] for r in rows) |
one entry per key |
| totals per key | defaultdict(float) in a loop |
one entry per key |
| top n | heapq.nlargest(n, it, key=...) |
n items |
| last n | deque(it, maxlen=n) |
n items |
| rolling window | deque(maxlen=n) + append() in the loop |
n items per key |
| first match | next((x for x in it if cond), None) |
constant; stops early |
| any / all | any(cond for x in it), all(...) |
constant; stops early |
| a file | writer.writerow() inside the loop |
constant |
from heapq import nlargestfrom statistics import fmean
window: deque[float] = deque(maxlen=3)rolling = []for t in [20.21, 20.22, 20.16, 19.93, 19.9]: window.append(t) # the oldest value drops out when full if len(window) == 3: rolling.append(round(fmean(window), 2))print(rolling)biggest = nlargest(2, read_rows("data/stores.csv"), key=lambda s: int(s["size_sqm"]))print([s["city"] for s in biggest])print(deque(range(10), maxlen=3))[20.2, 20.1, 20.0]['New York', 'Houston']deque([7, 8, 9], maxlen=3)Type hints for iterators
Section titled “Type hints for iterators”Hint (from collections.abc) |
Means | Use for |
|---|---|---|
Iterable[T] |
anything you can loop over | parameters: accept lists and streams |
Iterator[T] |
an object with __next__ (and __iter__ returning itself) |
return type of most generators |
Generator[Y, S, R] |
yields Y, receives S via send(), returns R |
generators whose callers use close(), send(), throw(), inspect.getgeneratorstate() or a return value |
Accept Iterable, return Iterator. Import them from collections.abc, not typing.
Gotchas
Section titled “Gotchas”- One pass only. A second loop over an iterator or generator gets nothing:
sum()returns 0 andmax()raisesValueError: max() iterable argument is empty. Compute everything in one loop, re-create the stream, or use a re-iterable class. - Lazy means not yet. Calling a generator function runs nothing. A side Counter filled by a stage is empty until the sink has consumed the stream.
- Close the file inside the generator. A
with open(...)block outside the generator closes the file before the consumer reads it:ValueError: I/O operation on closed file. - Early stop leaves files open. A generator paused inside
withkeeps its file open until it is closed or deleted. Callgen.close()or usecontextlib.closing(gen). groupbygroups runs, not keys. Sort by the key first, or use aCounter/defaultdictsink. Consume each group before you move on.isliceon a list restarts. Calliter()once before slicing in a loop, or usebatched.next()removes the item. After a peek, put it back withchain([item], it).teebuffers. If one copy runs ahead,teestores the gap; if one copy runs to the end first, it stores everything. Never use the original iterator aftertee.- No
len()or indexing on generators. Count withsum(1 for _ in gen)(this consumes it). raise StopIterationin a generator becomesRuntimeError. End withreturn.- Blank CSV cells are
"", notNone. Testif not cell, and convert numbers only after the test. Test parsed values withis None, because0.0is falsy. batchedyields tuples, and its last batch can be short.