10. Iterators and generators
Part 1 loaded every file into a list and then worked on the list. That works for 20,228 sales lines. It fails for a 20 GB log file or a sensor feed that never ends. This module teaches you to process data as a stream: one item at a time, with only that item in memory. The tools are iterators, generators and the itertools module. They are the core of every data pipeline written in plain Python.
From this module on, the code uses type hints: notes such as -> Iterator[str] that say what a function takes and returns. Python does not check them when the code runs. They help the reader and your editor. Module 12 teaches them in depth.
What you will learn
Section titled “What you will learn”- Explain the iteration protocol (
iter(),next()andStopIteration) and what aforloop does behind the scenes. - Write an iterator class with
__iter__and__next__, and a re-iterable class that can be looped over many times. - Write generator functions with
yield, predict their evaluation order and inspect their state. - Choose between a generator expression and a list comprehension, and measure the memory difference.
- Build lazy pipelines (read → parse → filter → aggregate) that stream
data/sales.csvanddata/sensors.csvrow by row and in chunks of N rows. - Apply
itertoolstools to streams (batched,islice,takewhile,dropwhile,chain.from_iterable,groupby,accumulate,tee) and the recipes of theitertoolsdocs, and avoid the one-pass exhaustion bug.
Prerequisites
Section titled “Prerequisites”- Part 1 checkpoint: you can write functions, loops and comprehensions without help.
- 04. Data structures: lists, dicts, tuples and comprehensions.
- 05. Functions: defining functions, closures and the lazy
map()andfilter(). - 07. Files and data formats:
open(),withandcsv.DictReader. - 09. Standard library power tools:
collections(Counter,defaultdict,deque,namedtuple),itertoolsanddatetime.
Concepts
Section titled “Concepts”Why stream data
Section titled “Why stream data”Compare two ways to total the revenue of data/sales.csv:
- Eager: read all 20,228 rows into a list, then add up the
revenuecolumn. The whole file sits in memory. - Lazy: read one row, add its revenue, forget the row, read the next row. Only one row sits in memory.
Eager evaluation computes all values at once and stores them. Lazy evaluation (module 05) computes each value only when someone asks for it. A stream is a sequence of items that you process one at a time, in order, often without knowing how many items will come.
| Eager (list) | Lazy (stream) | |
|---|---|---|
| Memory | grows with the data | constant: one item at a time |
| First result | after all items are read | after the first item |
| Passes over the data | as many as you like | one, then it is used up |
len(), indexing, .sort() |
yes | no |
| Infinite input (a live feed) | impossible | fine |
| Best for | small data you reuse | big files, logs, feeds, pipelines |
The lazy column is the reason this module exists. A laptop with 16 GB of memory can stream a 200 GB file. It cannot load it.
Iterables and iterators: the iteration protocol
Section titled “Iterables and iterators: the iteration protocol”Module 03 defined an iterable: any object that a for loop can walk through, such as a list, a string, a dict or a file. This module adds the object that does the walking.
An iterator is an object that gives the next item each time you ask, and remembers where it is. Two built-in functions talk to iterators:
iter(iterable)asks an iterable for a new iterator.next(iterator)asks the iterator for its next item. When no items are left, the iterator raises the exceptionStopIteration.
These rules form the iteration protocol: the agreement between the code that loops and the object that it loops over.
sensor_ids = ["S1", "S2", "S3"]it = iter(sensor_ids)print(type(it).__name__)print(next(it))print(next(it))print(next(it))list_iteratorS1S2S3The list holds the data. The iterator holds only a position in the list. Each next() moves the position by one. A fourth next() finds no item:
print(next(it))StopIterationStopIteration is not a real error. It is the signal “there are no more items”. Give next() a second argument to get a default value instead of the exception: next(it, None) returns None when the iterator is used up.
A for loop uses the protocol for you. These two pieces of code do the same thing:
readings = [20.21, 20.22, 20.16]
for value in readings: print("for loop:", value)
it = iter(readings) # what the for loop does behind the sceneswhile True: try: value = next(it) except StopIteration: break print("by hand: ", value)for loop: 20.21for loop: 20.22for loop: 20.16by hand: 20.21by hand: 20.22by hand: 20.16sequenceDiagram
participant L as for loop
participant I as iterator
L->>I: iter(readings)
L->>I: next()
I-->>L: 20.21
L->>I: next()
I-->>L: 20.22
L->>I: next()
I-->>L: 20.16
L->>I: next()
I-->>L: raises StopIteration
Note over L: the loop ends quietly
Every iterator is also an iterable: calling iter() on an iterator returns the same object. Many built-ins return iterators. Containers do not.
| Object | Iterable | Iterator (iter(x) is x) |
|---|---|---|
list, tuple, str, dict, set, range |
yes | no: each iter() gives a fresh iterator |
| an open file | yes | yes: it yields one line per next() |
csv.reader(f), csv.DictReader(f) |
yes | yes |
map(), filter(), zip(), enumerate(), reversed() |
yes | yes |
| a generator | yes | yes |
import csv
with open("data/sales.csv", encoding="utf-8", newline="") as f: reader = csv.DictReader(f) print(iter(reader) is reader, iter(f) is f) first = next(reader) second = next(reader)print(first["order_id"], first["revenue"])print(second["order_id"], second["revenue"])print(iter(sensor_ids) is sensor_ids)True TrueO000001 66.49O000002 14.99Falsecsv.DictReader is an iterator over the file. It takes one line of the file per next(), turns it into a dict and gives it to you. The file object reads ahead in a buffer: a fixed-size block of the file (a few KB) that Python reads at once, so apart from that one small block, the rest of the file is not read yet. This is the building block of every streaming pipeline in this module.
Writing an iterator class
Section titled “Writing an iterator class”You can make your own iterator. A class is a blueprint for objects; module 18 teaches classes in depth. For an iterator, you need only three methods:
__init__(self, ...)stores the starting state.selfis the object being built.__iter__(self)returns the iterator itself.__next__(self)returns the next item or raisesStopIteration.
Module 08 introduced dunder names, with two underscores on each side; methods with such names are dunder methods. You do not call them yourself. Python calls them: iter(x) calls x.__iter__(), and next(x) calls x.__next__(). Module 20 covers the full list.
data/sensors.csv has one reading every 10 minutes per sensor. This iterator produces those timestamps, so you can check that no reading is missing:
from datetime import datetime, timedeltafrom typing import Self
class TenMinuteClock: """Iterator over timestamps from start to end, every 10 minutes."""
def __init__(self, start: datetime, end: datetime) -> None: self.current = start self.end = end self.step = timedelta(minutes=10)
def __iter__(self) -> Self: return self
def __next__(self) -> datetime: if self.current > self.end: raise StopIteration value = self.current self.current += self.step return value
clock = TenMinuteClock(datetime(2024, 5, 1, 0, 0), datetime(2024, 5, 1, 0, 30))for ts in clock: print(ts.isoformat())print("second loop:", list(clock))2024-05-01T00:00:002024-05-01T00:10:002024-05-01T00:20:002024-05-01T00:30:00second loop: []The object keeps its state in self.current. Each __next__ call returns the current time and moves it forward. The second loop gets nothing: the iterator already reached the end, and it never rewinds. Self (from typing) is the type hint for “an object of this same class”.
Count the timestamps of the whole log period. The generator expression in sum() adds 1 per item; Generator expressions explains it.
full_period = TenMinuteClock(datetime(2024, 5, 1), datetime(2024, 5, 14, 23, 50))print(sum(1 for _ in full_period))201614 days × 144 readings per day = 2,016 readings per sensor, which is the row count of each sensor in data/sensors.csv. The iterator never stored the 2,016 timestamps; it made each one on demand.
Generator functions and yield
Section titled “Generator functions and yield”The class above needs 15 lines for a simple idea. A generator function says the same thing in 5. It is a function that contains the keyword yield. yield value hands one value to the caller and pauses the function at that line. The next next() call resumes the function right after the yield.
from collections.abc import Iterator
def ten_minute_clock(start: datetime, end: datetime) -> Iterator[datetime]: """Yield timestamps from start to end, every 10 minutes.""" current = start while current <= end: yield current current += timedelta(minutes=10)
gen = ten_minute_clock(datetime(2024, 5, 1, 0, 0), datetime(2024, 5, 1, 0, 30))print(type(gen).__name__)print([ts.strftime("%H:%M") for ts in gen])generator['00:00', '00:10', '00:20', '00:30']Calling a generator function does not run its body. It returns a generator object (or generator): an iterator that runs the body step by step, one next() at a time. When the body ends, the generator raises StopIteration for you. You never write __iter__, __next__ or raise StopIteration.
The hint Iterator[datetime] (from collections.abc) says “this returns an iterator of datetime values”. It is right when callers only loop or call next(), which covers most generators. Generator[YieldType, SendType, ReturnType] is the full form. Use it, as Generator[T, None, None], when callers also call generator methods such as close(), send() or throw(), or pass the generator to inspect.getgeneratorstate(): a type checker such as mypy (module 12) rejects these calls on a plain Iterator.
Generator state and laziness
Section titled “Generator state and laziness”A generator remembers its local variables between next() calls. Its state is the line where it paused plus the values of its variables. Prints show the order in which the code runs:
import inspectfrom collections.abc import Generator
def read_temps(values: list[float]) -> Generator[float, None, None]: print(" [gen] start") for v in values: print(f" [gen] yield {v}") yield v print(" [gen] end")
gen = read_temps([20.21, 20.22, 20.16])print("created:", inspect.getgeneratorstate(gen))print("caller got", next(gen))print("paused:", inspect.getgeneratorstate(gen))print("caller got", next(gen))for t in gen: print("loop got", t)print("finished:", inspect.getgeneratorstate(gen))created: GEN_CREATED [gen] start [gen] yield 20.21caller got 20.21paused: GEN_SUSPENDED [gen] yield 20.22caller got 20.22 [gen] yield 20.16loop got 20.16 [gen] endfinished: GEN_CLOSEDRead the output line by line:
- Creating the generator printed nothing. The body has not started (
GEN_CREATED). - The first
next()ran the body from the top to the firstyield, then paused (GEN_SUSPENDED). - Each later
next()resumed after theyieldand ran to the next one. - The
forloop took the last value. Its next request ran the body to the end;[gen] endprinted, and the generator raisedStopIteration, which ended the loop (GEN_CLOSED).
stateDiagram-v2
[*] --> Created: call the function
Created --> Running: next()
Running --> Suspended: yield value
Suspended --> Running: next()
Running --> Closed: body ends (StopIteration)
Suspended --> Closed: close()
This is laziness: the generator does work only when the consumer asks. The consumer is the code that calls next(), directly or through a for loop, sum(), list() and so on. Nothing asks, nothing runs.
A generator stops early when the consumer stops asking. Call close() to end it on purpose: Python raises GeneratorExit at the paused yield, so finally blocks and with blocks inside the generator run. This matters when a generator holds an open file:
from itertools import islice
def file_lines(path: str) -> Generator[str, None, None]: with open(path, encoding="utf-8") as f: try: for line in f: yield line.rstrip("\n") finally: print(" [gen] file closed")
lines = file_lines("data/readings.txt")print(list(islice(lines, 3)))lines.close()print("after close:", inspect.getgeneratorstate(lines))['21.0', '21.9', '21.4'] [gen] file closedafter close: GEN_CLOSEDislice(lines, 3) takes only the first 3 lines (see itertools for streams). The generator is then paused inside the with block, so the file is still open. close() resumes it with GeneratorExit, the with block closes the file, and the finally runs. Without close(), the file closes only when Python deletes the generator object. Module 11 shows contextlib.closing, which calls close() for you.
Generator expressions vs list comprehensions
Section titled “Generator expressions vs list comprehensions”A generator expression looks like a list comprehension with parentheses instead of square brackets. It builds a generator, not a list.
| List comprehension | Generator expression | |
|---|---|---|
| Syntax | [float(r) for r in raw] |
(float(r) for r in raw) |
| Result | a list, all values computed now |
a generator, values computed on demand |
| Memory | grows with the number of items | constant, about 200 bytes |
| Reuse | loop over it many times | one pass only |
len(), [i], .sort() |
yes | no |
| As the only argument of a call | sum([x for x in it]) |
sum(x for x in it): no extra parentheses |
sorted(stream) works on a generator too, but it loads every item into a list first, so the memory benefit is gone.
sys.getsizeof() returns the size in bytes of one object:
import sys
squares_list = [n * n for n in range(1_000_000)]squares_gen = (n * n for n in range(1_000_000))print(f"list: {sys.getsizeof(squares_list):>9,} bytes")print(f"generator: {sys.getsizeof(squares_gen):>9,} bytes")print(sum(squares_gen) == sum(squares_list))list: 8,448,728 bytesgenerator: 200 bytesTrueThe list stores one million references; that is about 8 MB before you count the numbers themselves. sys.getsizeof() measures only the outer object, so the real cost of the list is higher still. The generator stores only its paused state, whatever the number of items. Your byte counts can differ a little between Python versions; the ratio does not.
Use a list comprehension when the data is small, or when you need len(), indexing, sorting or more than one pass. Use a generator expression when you consume the values once, especially inside sum(), max(), min(), any(), all(), "".join() or a for loop. any() and all() also stop early: any(t > 40 for t in temps) stops at the first hot reading.
Delegating with yield from
Section titled “Delegating with yield from”yield from iterable yields every item of another iterable, one by one. It replaces the loop for item in iterable: yield item. The generator delegates to the inner iterable: it passes its items on until the inner one is used up.
The six files in data/reports/ each hold one month of 2024 sales. One generator can stream them as one sequence of rows:
from pathlib import Path
def rows_from_files(paths: list[Path]) -> Iterator[dict[str, str]]: """Yield the rows of several CSV files as one stream.""" for path in paths: with open(path, encoding="utf-8", newline="") as f: yield from csv.DictReader(f)
paths = sorted(Path("data/reports").glob("*.csv"))rows = rows_from_files(paths)print(next(rows)["order_date"])print(sum(1 for _ in rows) + 1)2024-01-02297Each file opens only when the stream reaches it and closes before the next one opens. DictReader reads columns by name, so the file 2024-04.csv, whose columns come in another order, needs no special code. yield from also forwards close() to the inner generator, so delegation keeps cleanup working.
Lazy pipelines
Section titled “Lazy pipelines”A pipeline is a chain of steps in which the output of one step is the input of the next. Each step is a stage. In a lazy pipeline, each stage is a generator that takes an iterator and returns an iterator. A pipeline has three kinds of stage:
- the source produces raw items (it reads a file, a database or an API);
- the transforms parse, clean, filter or enrich the items, one at a time;
- the sink consumes the stream and produces a result: a total, a dict of counts, a file, rows in a database.
flowchart LR
A["read_rows()<br/>source"] --> B["parse()<br/>transform"]
B --> C["only_2024()<br/>filter"]
C --> D["sum / dict<br/>sink"]
Nothing runs until the sink asks for an item. Then the request travels backward, and one item travels forward through every stage. Prints in each stage show this order:
def source(lines: list[str]) -> Iterator[str]: for line in lines: print(f"read {line}") yield line
def parse(lines: Iterator[str]) -> Iterator[tuple[str, float]]: for line in lines: order_id, revenue = line.split(",") print(f"parse {order_id}") yield order_id, float(revenue)
def big_orders(orders: Iterator[tuple[str, float]]) -> Iterator[tuple[str, float]]: for order_id, revenue in orders: if revenue >= 100: print(f"keep {order_id}") yield order_id, revenue
raw = ["O000004,249.0", "O000005,14.99", "O000006,1299.0"]pipeline = big_orders(parse(source(raw)))print("pipeline built, nothing read yet")total = sum(revenue for _, revenue in pipeline)print("total:", total)pipeline built, nothing read yetread O000004,249.0parse O000004keep O000004read O000005,14.99parse O000005read O000006,1299.0parse O000006keep O000006total: 1548.0The output reads like a conveyor belt. Order O000004 goes through all stages before O000005 is even read. O000005 stops at the filter. At any moment, only one order is in flight, whatever the size of the input. That is why a lazy pipeline can process a file of any size in constant memory.
Each stage is a small function that does one job, so you can test it alone and reuse it in other pipelines. Worked example 1 builds this pipeline on the real data/sales.csv.
Processing in chunks
Section titled “Processing in chunks”Some sinks work better with groups of items than with single items. A database inserts 5,000 rows in one call much faster than in 5,000 calls. A web API accepts at most 100 records per request. A chunk (or batch) is a group of up to N consecutive items of a stream.
itertools.batched(iterable, n) (Python 3.12+) yields tuples of n items. The last tuple holds the rest.
from itertools import batched
order_ids = [f"O{n:06d}" for n in range(1, 11)]for batch in batched(order_ids, 4): print(len(batch), batch)4 ('O000001', 'O000002', 'O000003', 'O000004')4 ('O000005', 'O000006', 'O000007', 'O000008')2 ('O000009', 'O000010')Ten items in batches of 4 give 4 + 4 + 2. Only one batch is in memory at a time. From Python 3.13, batched(it, n, strict=True) raises a ValueError when the last batch is short, for data that must split evenly.
Before Python 3.12, people wrote the same tool with islice. The recipe is worth knowing, because you meet it in older code:
from collections.abc import Iterable
def chunked(iterable: Iterable[str], n: int) -> Iterator[list[str]]: """Yield lists of up to n items (like itertools.batched).""" it = iter(iterable) while chunk := list(islice(it, n)): yield chunk
print([len(c) for c in chunked(order_ids, 4)])[4, 4, 2]The := operator (the walrus operator) assigns a value and returns it in one expression. Here it stores the chunk and tests it: an empty list is falsy, so the loop stops when islice finds no more items. Calling iter() first matters: islice on a list would start from the beginning every time.
pandas has the same idea for big CSV files. pd.read_csv(path, chunksize=n) returns an iterator of DataFrames with n rows each (module 24 teaches DataFrames):
import pandas as pd
total = 0.0with pd.read_csv("data/sales.csv", chunksize=5_000) as reader: for chunk in reader: total += chunk["revenue"].sum()print(f"{total:,.2f}")3,596,523.83itertools for streams
Section titled “itertools for streams”The itertools module (module 09) is a toolbox of lazy building blocks. Each tool takes iterables and returns an iterator, so the tools plug into any pipeline.
| Tool | What it yields | Stream use |
|---|---|---|
islice(it, stop), islice(it, start, stop) |
a slice of a stream, by position | preview the first rows; skip a header block |
takewhile(pred, it) |
items while pred(item) is true, then stops |
read a date-sorted file up to a cut-off date |
dropwhile(pred, it) |
skips items while pred(item) is true, then yields the rest |
start a date-sorted file at a given date |
chain(a, b, ...) |
the items of a, then of b, … |
join a few streams |
chain.from_iterable(its) |
the items of each iterable in its |
flatten a stream of streams (files, pages, batches) |
batched(it, n) |
tuples of up to n items |
bulk inserts, API batches |
groupby(it, key) |
(key, group) for each run of equal keys |
daily totals from a date-sorted file |
accumulate(it) |
running totals | cumulative revenue |
pairwise(it) |
(a, b), (b, c), … |
gaps and changes between consecutive readings |
tee(it, n) |
n independent iterators over one stream |
two consumers of one stream (with care) |
count(start) |
start, start + 1, … forever |
ids, row numbers |
A predicate (module 05) is a function that returns True or False. islice is the lazy version of slicing: a generator has no [0:5], so islice(gen, 5) takes its first five items. takewhile and dropwhile are useful because data/sales.csv is sorted by date:
from itertools import dropwhile, takewhile
def sales_rows() -> Iterator[dict[str, str]]: with open("data/sales.csv", encoding="utf-8", newline="") as f: yield from csv.DictReader(f)
from_2024 = dropwhile(lambda r: r["order_date"] < "2024-01-01", sales_rows())new_year = takewhile(lambda r: r["order_date"] < "2024-01-02", from_2024)print([r["order_id"] for r in islice(new_year, 3)])print(sum(1 for _ in new_year) + 3, "lines on 2024-01-01")['O006722', 'O006723', 'O006723']16 lines on 2024-01-01ISO dates (YYYY-MM-DD) sort as text in date order, so a plain string comparison works. O006723 appears twice because one order can have several lines. dropwhile reads and drops the 2023 rows. takewhile stops at the first row of January 2. It reads that one row to know it must stop and then drops it.
groupby groups consecutive items with the same key. On a sorted stream, it gives one group per key, without loading the file:
from itertools import groupby
daily = groupby(sales_rows(), key=lambda r: r["order_date"])for day, lines in islice(daily, 3): revenue = sum(float(r["revenue"]) for r in lines) print(day, f"{revenue:9,.2f}")2023-01-01 4,767.042023-01-02 1,593.882023-01-03 1,811.84Each lines is a lazy iterator over the rows of one day. It shares the source with daily, so use it before you move to the next group. On unsorted data, groupby starts a new group every time the key changes, and the same key appears in many groups. Sort first, or use a defaultdict sink.
chain.from_iterable flattens a stream of iterables. It is the itertools way to say yield from in a loop:
from itertools import chain
batches = [["S1", "S2"], ["S3"], ["S4"]]print(list(chain.from_iterable(batches)))print(list(chain(["S1", "S2"], ["S3", "S4"])))['S1', 'S2', 'S3', 'S4']['S1', 'S2', 'S3', 'S4']tee(it, n) splits one iterator into n independent iterators. It has three caveats:
teestores every item that one copy has seen and another copy has not. If one copy runs to the end before the other starts,teestores the whole stream. That is no better than a list.- After the split, do not use the original iterator. Every item you take from it is lost to the copies.
- The copies are not safe to use from several threads at once.
from itertools import tee
stream = iter([20.21, 20.22, 20.16, 19.93])a, b = tee(stream)print(next(a), next(b))print(next(stream), "<- taken from the original")print(list(a), list(b))20.21 20.2120.22 <- taken from the original[20.16, 19.93] [20.16, 19.93]The value 20.22 went to stream, so neither copy sees it. Use tee only when the copies stay close to each other, for example with pairwise-style look-ahead. To compute two results from one stream, a single loop that updates both is simpler and uses less memory (see Example 7).
Recipes from the itertools docs
Section titled “Recipes from the itertools docs”A recipe is a short helper function built from the basic itertools tools. The Python documentation has a section called “Itertools Recipes” with about 40 of them. They are not in the standard library: you copy the ones you need, or install the package more-itertools, which ships all of them and many more (uv add more-itertools, then from more_itertools import sliding_window). Four recipes are especially useful on data streams:
from collections import dequefrom collections.abc import Callable
def take[T](n: int, iterable: Iterable[T]) -> list[T]: """Return the first n items as a list.""" return list(islice(iterable, n))
def sliding_window[T](iterable: Iterable[T], n: int) -> Iterator[tuple[T, ...]]: """Yield overlapping windows of n consecutive items.""" it = iter(iterable) window = deque(islice(it, n - 1), maxlen=n) for x in it: window.append(x) yield tuple(window)
def unique_everseen[T](iterable: Iterable[T]) -> Iterator[T]: """Yield each distinct item once, in first-seen order.""" seen: set[T] = set() for x in iterable: if x not in seen: seen.add(x) yield x
def first_true[T](iterable: Iterable[T], pred: Callable[[T], bool]) -> T | None: """Return the first item for which pred is true, or None.""" return next(filter(pred, iterable), None)The [T] after a function name makes the function generic: T stands for any item type, so take(3, rows) returns a list of rows and take(3, temps) a list of floats. This syntax needs Python 3.12+; module 12 explains it. The docs’ first_true also takes a default value; this version always returns None when nothing matches.
print([r["order_id"] for r in take(3, sales_rows())])temps = [20.21, 20.22, 20.16, 19.93, 19.9, 20.12]print([round(sum(w) / 3, 2) for w in sliding_window(temps, 3)])first_ids = (r["order_id"] for r in take(10, sales_rows()))print(list(unique_everseen(first_ids)))big = first_true(sales_rows(), lambda r: float(r["revenue"]) > 1000)assert big is not None # first_true returns None when nothing matchesprint(big["order_id"], big["order_date"], big["product"], big["revenue"])['O000001', 'O000002', 'O000003'][20.2, 20.1, 20.0, 19.98]['O000001', 'O000002', 'O000003', 'O000004', 'O000005', 'O000006', 'O000007', 'O000008']O000006 2023-01-01 14-inch Ultrabook Laptop 2183.1sliding_window is the rolling window that Example 4 builds by hand, as a reusable tool. The first 10 lines hold only 8 orders, because some orders have several lines. unique_everseen keeps a set of every item it has seen, so its memory grows with the number of distinct items: fine for order ids, not for every row of a huge file. first_true stops reading the file at the first match.
| Recipe (docs or more-itertools) | What it does | Stream use |
|---|---|---|
take(n, it) |
first n items as a list |
preview a file |
sliding_window(it, n) |
overlapping windows of n items |
rolling statistics |
unique_everseen(it, key=None) |
each distinct item once, in order | de-duplicate ids |
first_true(it, default, pred) |
first item where pred is true |
find the first anomaly |
consume(it, n) |
advance n items (or to the end) |
skip a header block |
nth(it, n, default) |
the item at position n |
sample one row |
partition(pred, it) |
two iterators: false items, true items | split good and bad rows |
roundrobin(*its) |
one item from each iterator in turn | interleave several feeds |
The one-pass exhaustion gotcha
Section titled “The one-pass exhaustion gotcha”An iterator gives each item once. After the last item, it is exhausted: every later loop gets nothing, and no error tells you. This is the most common iterator bug:
temps = (float(t) for t in ["20.21", "20.22", "20.16"])print("max:", max(temps))print("sum:", sum(temps))print("as list:", list(temps))max: 20.22sum: 0as list: []max() used up the generator. sum() then saw an empty stream and returned 0, which looks like a real result. max() on an exhausted iterator is louder:
print(max(temps))ValueError: max() iterable argument is emptyFour fixes, from best to worst for big data:
| Fix | How | Cost |
|---|---|---|
| One pass | one loop updates every result (total, count, max) | constant memory |
| Re-create the stream | call the generator function again for each pass | reads the source again |
| A re-iterable class | its __iter__ returns a fresh generator each time |
reads the source again; looks like a list to the caller |
| Store it | values = list(stream) |
memory grows with the data; fine when small |
A re-iterable object gives a fresh iterator each time you call iter() on it. A list is re-iterable. You can write your own: put a yield in __iter__, and each loop gets a new generator.
class SensorColumn: """Re-iterable view of one numeric column of data/sensors.csv."""
def __init__(self, path: str, column: str) -> None: self.path = path self.column = column
def __iter__(self) -> Iterator[float]: with open(self.path, encoding="utf-8", newline="") as f: for row in csv.DictReader(f): if row[self.column]: # skip blank cells yield float(row[self.column])
temps = SensorColumn("data/sensors.csv", "temperature_c")print("max:", max(temps))print("min:", min(temps))print("count:", sum(1 for _ in temps))max: 44.89min: 18.56count: 8042Each loop reads the file again from the top, so each one sees all 8,042 non-blank readings (8,064 rows minus 22 blanks). The class holds only the path and the column name, never the data.
Worked examples
Section titled “Worked examples”Example 1 — Stream sales.csv into revenue by channel
Section titled “Example 1 — Stream sales.csv into revenue by channel”Goal: The finance team wants 2024 revenue by sales channel (store or online). Compute it from data/sales.csv with a lazy pipeline that never holds more than one row, and prove that it uses far less memory than loading the file.
Step 1 — Write the source stage
Section titled “Step 1 — Write the source stage”import csvfrom collections.abc import Iteratorfrom itertools import islice
def read_rows(path: str) -> Iterator[dict[str, str]]: """Source: yield each CSV row as a dict of strings.""" with open(path, encoding="utf-8", newline="") as f: yield from csv.DictReader(f)
for row in islice(read_rows("data/sales.csv"), 2): print(row["order_id"], row["order_date"], row["channel"], row["revenue"])O000001 2023-01-01 online 66.49O000002 2023-01-01 store 14.99read_rows is a generator, so calling it opens nothing. islice asks for 2 rows, so Python reads only the first buffer of the file. Every value is still a str.
Step 2 — Parse each row into typed values
Section titled “Step 2 — Parse each row into typed values”from typing import NamedTuple
class Sale(NamedTuple): order_date: str channel: str category: str quantity: int revenue: float
def parse_sales(rows: Iterator[dict[str, str]]) -> Iterator[Sale]: """Transform: keep the needed columns and convert their types.""" for row in rows: yield Sale( order_date=row["order_date"], channel=row["channel"], category=row["category"], quantity=int(row["quantity"]), revenue=float(row["revenue"]), )
first = next(parse_sales(read_rows("data/sales.csv")))print(first)print(first.revenue * 2)Sale(order_date='2023-01-01', channel='online', category='Home', quantity=1, revenue=66.49)132.98typing.NamedTuple builds a tuple type with named, typed fields: the class form of the namedtuple from module 09 (module 21 compares it with dataclasses). A Sale uses less memory than a dict, and first.revenue reads better than row["revenue"]. The parse stage keeps 5 of the 13 columns, which also saves memory downstream.
Step 3 — Filter the rows of 2024
Section titled “Step 3 — Filter the rows of 2024”def only_year(sales: Iterator[Sale], year: str) -> Iterator[Sale]: """Filter: keep the sales of one year.""" return (s for s in sales if s.order_date.startswith(year))
sales_2024 = only_year(parse_sales(read_rows("data/sales.csv")), "2024")print(next(sales_2024).order_date)2024-01-01A one-line filter needs no yield: a function can return a generator expression. The first 2024 row appears only after the stage has read and dropped every 2023 row.
Step 4 — Aggregate in the sink
Section titled “Step 4 — Aggregate in the sink”from collections import defaultdict
def revenue_by(sales: Iterator[Sale], field: str) -> dict[str, float]: """Sink: total revenue per value of one field.""" totals: defaultdict[str, float] = defaultdict(float) for sale in sales: totals[getattr(sale, field)] += sale.revenue return dict(totals)
pipeline = only_year(parse_sales(read_rows("data/sales.csv")), "2024")by_channel = revenue_by(pipeline, "channel")for channel, revenue in sorted(by_channel.items()): print(f"{channel:<7}{revenue:>14,.2f}")print(f"{'total':<7}{sum(by_channel.values()):>14,.2f}")online 896,613.41store 1,054,320.83total 1,950,934.24The sink is the only stage with a loop that drives the pipeline. getattr(sale, field) reads the field whose name is in the string field, so the same sink groups by "channel" or "category". The 2024 total matches the data dictionary: 1,950,934.24.
Step 5 — Measure the memory
Section titled “Step 5 — Measure the memory”import tracemalloc
def eager_total(path: str) -> float: with open(path, encoding="utf-8", newline="") as f: rows = list(csv.DictReader(f)) # every row in memory return sum(float(r["revenue"]) for r in rows)
def lazy_total(path: str) -> float: return sum(s.revenue for s in parse_sales(read_rows(path)))
for func in (eager_total, lazy_total): tracemalloc.start() total = func("data/sales.csv") _, peak = tracemalloc.get_traced_memory() tracemalloc.stop() print(f"{func.__name__}: total {total:,.2f}, peak {peak / 1000:,.0f} KB")eager_total: total 3,596,523.83, peak 21,160 KBlazy_total: total 3,596,523.83, peak 41 KBThe tracemalloc module traces the memory that Python allocates; get_traced_memory() returns the current and the peak (highest) size. The eager version peaks at about 21 MB for a 1.9 MB file, because each row becomes a dict of 13 strings, while the lazy version peaks at about 41 KB: one row, one Sale and the read buffer. A file 100 times bigger would need 100 times the memory eagerly and the same 41 KB lazily (your numbers can differ a little between Python versions).
Common mistakes:
- Returning a list from a stage (
return [s for s in sales if ...]). The pipeline still works, but that stage loads everything and the memory benefit is gone. Return a generator. - Opening the file outside the generator and closing it before the sink runs. A
withblock that ends before you consume the stream givesValueError: I/O operation on closed file. Open the file inside the source generator. - Reusing
pipelinefor a second report. It is exhausted after the first sink. Build a new pipeline for each pass.
Example 2 — Load sales into SQLite in chunks of 5,000 rows
Section titled “Example 2 — Load sales into SQLite in chunks of 5,000 rows”Goal: A nightly job copies data/sales.csv into a database table. Inserting row by row is slow, and loading the whole file first wastes memory. Stream the file and insert it in chunks of 5,000 rows.
Step 1 — Split the stream into chunks
Section titled “Step 1 — Split the stream into chunks”from itertools import batched
sizes = [len(chunk) for chunk in batched(read_rows("data/sales.csv"), 5_000)]print(sizes)print(sum(sizes))[5000, 5000, 5000, 5000, 228]2022820,228 rows give four full chunks and one chunk of 228. Each chunk is a tuple of row dicts. Only one chunk is alive at a time, because the list comprehension keeps only its length.
Step 2 — Create the target table
Section titled “Step 2 — Create the target table”import sqlite3
con = sqlite3.connect(":memory:")con.execute( "CREATE TABLE sales (order_id TEXT, order_date TEXT, store_id TEXT," " product_id TEXT, quantity INTEGER, revenue REAL)")columns = ["order_id", "order_date", "store_id", "product_id", "quantity", "revenue"]placeholders = ", ".join("?" * len(columns))insert_sql = f"INSERT INTO sales VALUES ({placeholders})"print(insert_sql)INSERT INTO sales VALUES (?, ?, ?, ?, ?, ?)sqlite3 is the standard-library interface to SQLite, a database that lives in one file; ":memory:" creates a temporary one in memory. The ? marks are placeholders: SQLite fills them with the values of each record, safely quoted. Module 30 teaches SQL; here you need only one table.
Step 3 — Insert one chunk per call
Section titled “Step 3 — Insert one chunk per call”converters = {"quantity": int, "revenue": float} # the other columns stay str
def to_record(row: dict[str, str]) -> tuple[str | int | float, ...]: return tuple(converters.get(c, str)(row[c]) for c in columns)
calls = 0for chunk in batched(read_rows("data/sales.csv"), 5_000): records = (to_record(row) for row in chunk) con.executemany(insert_sql, records) calls += 1con.commit()print("executemany calls:", calls)executemany calls: 5to_record picks the columns in table order and converts the two numeric ones; converters.get(c, str) falls back to str for the rest. executemany sends many records with one statement. The generator records converts the rows of one chunk as executemany asks for them.
Step 4 — Check the load
Section titled “Step 4 — Check the load”count, total = con.execute("SELECT COUNT(*), SUM(revenue) FROM sales").fetchone()print(count, f"{total:,.2f}")con.close()20228 3,596,523.83A load job should always check its result. The row count and the revenue total match the source file. Production jobs compare the counts automatically and fail loudly when they differ.
Common mistakes:
- Writing
for chunk in batched(rows, 5_000)whererowswas already used. The loop does nothing and the table stays empty. Create the stream right before the loop. - Expecting a list from
batched. It yields tuples. Convert withlist(chunk)if a library needs a list. - Choosing a tiny chunk size, such as 10. The job makes 2,023 calls instead of 5 and loses most of the speed gain. A few thousand rows per chunk is a common start.
Example 3 — Clean sensor readings with a generator chain
Section titled “Example 3 — Clean sensor readings with a generator chain”Goal: data/sensors.csv has blank cells in its three numeric columns. A monitoring job needs clean temperature readings: typed values, rows without a temperature removed, and a count of what was removed and why.
Step 1 — Look at raw rows
Section titled “Step 1 — Look at raw rows”sensor_rows = read_rows("data/sensors.csv")blank_rows = (r for r in sensor_rows if "" in r.values())for row in islice(blank_rows, 3): blanks = [column for column, value in row.items() if value == ""] print(row["timestamp"], row["sensor_id"], blanks, repr(row[blanks[0]]))2024-05-01T04:10:00 S2 ['temperature_c'] ''2024-05-01T13:30:00 S4 ['vibration_mm_s'] ''2024-05-01T15:50:00 S3 ['humidity_pct'] ''The filter scans the stream and keeps only rows with an empty cell. islice stops after the third one, so the rest of the file is never read. A blank cell arrives as the empty string "", not as None.
Step 2 — Parse a row into typed values
Section titled “Step 2 — Parse a row into typed values”from datetime import datetime
class Reading(NamedTuple): timestamp: datetime sensor_id: str temperature_c: float | None status: str
def to_float(text: str) -> float | None: """Convert a CSV cell to float; a blank cell becomes None.""" return float(text) if text else None
def parse_readings(rows: Iterator[dict[str, str]]) -> Iterator[Reading]: for row in rows: yield Reading( timestamp=datetime.fromisoformat(row["timestamp"]), sensor_id=row["sensor_id"], temperature_c=to_float(row["temperature_c"]), status=row["status"], )
first_reading = next(parse_readings(read_rows("data/sensors.csv")))print(first_reading.timestamp, first_reading.sensor_id, first_reading.temperature_c)print(type(first_reading.timestamp), type(first_reading.temperature_c))2024-05-01 00:00:00 S1 20.21<class 'datetime.datetime'> <class 'float'>The type hint float | None says “a float or None”. None is the honest value for a missing reading (module 01). datetime.fromisoformat() parses the ISO timestamp, so later stages can compare times and extract the date.
Step 3 — Drop the gaps and count them
Section titled “Step 3 — Drop the gaps and count them”from collections import Counter
def drop_missing( readings: Iterator[Reading], removed: Counter[str]) -> Iterator[Reading]: """Filter: skip readings without a temperature and count them per sensor.""" for r in readings: if r.temperature_c is None: removed[r.sensor_id] += 1 continue yield r
removed: Counter[str] = Counter()clean = drop_missing(parse_readings(read_rows("data/sensors.csv")), removed)kept = Counter(r.sensor_id for r in clean)print("kept: ", dict(sorted(kept.items())))print("removed:", dict(sorted(removed.items())))print(sum(kept.values()) + sum(removed.values()))kept: {'S1': 2010, 'S2': 2012, 'S3': 2010, 'S4': 2010}removed: {'S1': 6, 'S2': 4, 'S3': 6, 'S4': 6}8064A for loop or sum() sees only the yielded items, so a side result goes into an object that the stage updates, here a Counter. Read removed only after the sink has consumed the stream; before that, it is still empty. The two totals add up to all 8,064 rows.
Step 4 — Check the result
Section titled “Step 4 — Check the result”assert sum(removed.values()) == 22 # 22 blank temperatures in the dictionaryassert kept["S2"] == 2012 # 2,016 readings minus 4 blanksprint("checks passed")checks passedThe asserts compare the stream’s counts with known facts about the file. A cleaning stage that silently drops rows is a classic source of wrong reports, so count what you drop.
Common mistakes:
- Testing
if r.temperature_c:instead ofis None. A real reading of 0.0 °C is falsy and would be dropped. - Printing
removedbefore the pipeline has run. The Counter is still empty, because the generators have not started. - Converting with
float(row["temperature_c"])without a blank check. The first blank cell raisesValueError: could not convert string to float: ''.
Example 4 — Compute rolling statistics and flag spikes
Section titled “Example 4 — Compute rolling statistics and flag spikes”Goal: A temperature spike is a reading far above the recent normal. For each sensor, compare each reading with the mean of that sensor’s previous 6 readings (one hour) and flag readings more than 6 °C above it.
Step 1 — Write a rolling mean generator
Section titled “Step 1 — Write a rolling mean generator”from collections import dequefrom statistics import fmean
def rolling_mean(values: Iterable[float], window: int) -> Iterator[float]: """Yield the mean of the last `window` values, once the window is full.""" recent: deque[float] = deque(maxlen=window) for v in values: recent.append(v) if len(recent) == window: yield round(fmean(recent), 2)
s1_first = [20.21, 20.22, 20.16, 19.93, 19.9, 20.12, 20.11, 19.88]print(list(rolling_mean(s1_first, 3)))[20.2, 20.1, 20.0, 19.98, 20.04, 20.04]A rolling window (or sliding window) is the last N items of a stream; it moves forward by one item at a time. A deque with maxlen=3 drops its oldest item when a new one arrives, so it always holds the window; its means form the moving average of module 05. The first mean appears when the window is full: 8 values give 6 means.
Step 2 — Keep one window per sensor
Section titled “Step 2 — Keep one window per sensor”def flag_spikes( readings: Iterator[Reading], window: int = 6, jump: float = 6.0) -> Iterator[tuple[Reading, float]]: """Yield (reading, baseline) for readings far above their sensor's recent mean.""" recent: defaultdict[str, deque[float]] = defaultdict(lambda: deque(maxlen=window)) for r in readings: assert r.temperature_c is not None # drop_missing must run first temps = recent[r.sensor_id] if len(temps) == window: baseline = fmean(temps) if r.temperature_c - baseline > jump: yield r, baseline continue # keep the spike out of the baseline temps.append(r.temperature_c)data/sensors.csv interleaves the 4 sensors, so one deque is not enough. A defaultdict creates a fresh window the first time it sees a sensor. A spike does not enter its window, so it cannot raise the baseline for the next readings. The assert documents that blanks must be gone and tells a type checker that temperature_c is a float here.
Step 3 — Run the detector on the clean stream
Section titled “Step 3 — Run the detector on the clean stream”clean = drop_missing(parse_readings(read_rows("data/sensors.csv")), Counter())spikes = flag_spikes(clean)for r, baseline in islice(spikes, 3): print(f"{r.timestamp:%m-%d %H:%M} {r.sensor_id} {r.temperature_c:5.2f}" f" vs {baseline:5.2f}")05-01 10:40 S3 33.51 vs 22.1505-02 12:30 S1 36.03 vs 23.9005-02 13:20 S2 44.89 vs 27.31The format spec %m-%d %H:%M inside the f-string formats the datetime directly. The first three spikes sit 11 to 18 °C above their hour-long baseline. Normal readings move by a few tenths of a degree in 10 minutes.
Step 4 — Count spikes per sensor
Section titled “Step 4 — Count spikes per sensor”clean = drop_missing(parse_readings(read_rows("data/sensors.csv")), Counter())per_sensor = Counter(r.sensor_id for r, _ in flag_spikes(clean))print(dict(sorted(per_sensor.items())), sum(per_sensor.values())){'S1': 8, 'S2': 12, 'S3': 11, 'S4': 8} 39The data dictionary says that 40 temperature spikes were injected. The detector finds 39 of them, and the count stays the same for any threshold from 5 °C to 8 °C, so the rule is robust. The 40th spike is S2 at 00:40 on May 1, its fifth reading, before its window holds 6 values: a detector cannot judge the first window readings. The whole job holds 4 windows of 6 floats in memory, whatever the length of the log.
Common mistakes:
- Using one deque for all sensors. The window then mixes S1 and S4, whose normal temperatures differ by 4 °C, and the baseline is meaningless.
- Letting spikes into the window. One 40 °C reading lifts the baseline for the next hour and hides a second spike.
- Running the detector on the stream before
drop_missing.None - baselineraisesTypeError.
Example 5 — Daily revenue from a sorted stream
Section titled “Example 5 — Daily revenue from a sorted stream”Goal: A dashboard needs the daily revenue of the first week of December 2024 and the running total over that week. data/sales.csv is sorted by date, so compute both in one pass without loading the file.
Step 1 — Cut the stream to the date range
Section titled “Step 1 — Cut the stream to the date range”from itertools import dropwhile, takewhile
start, end = "2024-12-01", "2024-12-07"lines = parse_sales(read_rows("data/sales.csv"))in_range = takewhile( lambda s: s.order_date <= end, dropwhile(lambda s: s.order_date < start, lines),)first_line = next(in_range)print(first_line.order_date, first_line.category, first_line.revenue)2024-12-01 Home 111.98dropwhile skips every line before December 1. takewhile stops at the first line of December 8, so the job never reads the rest of the month. Both work only because the file is sorted by order_date.
Step 2 — Group the lines by day
Section titled “Step 2 — Group the lines by day”from itertools import chain, groupby
week = chain([first_line], in_range) # put the peeked line back in frontdaily = [ (day, round(sum(s.revenue for s in group), 2)) for day, group in groupby(week, key=lambda s: s.order_date)]for day, revenue in daily: print(day, f"{revenue:>10,.2f}")2024-12-01 14,585.642024-12-02 15,222.992024-12-03 7,475.262024-12-04 7,334.262024-12-05 9,823.312024-12-06 9,920.222024-12-07 12,009.16Step 1 removed one line from the stream with next(); chain([first_line], in_range) puts it back in front, or December 1 would miss a line. groupby then yields one group per day. Storing 7 daily totals in a list is fine: the list is small, and the stream behind it was never stored.
Step 3 — Add a running total
Section titled “Step 3 — Add a running total”from itertools import accumulate
running = accumulate(revenue for _, revenue in daily)for (day, revenue), cumulative in zip(daily, running, strict=True): print(day, f"{revenue:>10,.2f}", f"{cumulative:>11,.2f}")2024-12-01 14,585.64 14,585.642024-12-02 15,222.99 29,808.632024-12-03 7,475.26 37,283.892024-12-04 7,334.26 44,618.152024-12-05 9,823.31 54,441.462024-12-06 9,920.22 64,361.682024-12-07 12,009.16 76,370.84accumulate yields running sums: the first value, then the first two added, and so on. zip(..., strict=True) pairs each day with its running total and raises an error if the two streams have different lengths. December 2 is Cyber Monday, the biggest day of the week.
Common mistakes:
- Forgetting the peeked line. Any
next()on a stream removes that item. Put it back withchain(), or do not peek. - Using
groupbyon a file sorted by something else. Each change of key starts a new group, so one day can appear many times. Check the sort order or use adefaultdictsink. - Calling
list(group)after moving to the next group. The old group is already exhausted, because all groups share one underlying stream.
Example 6 — Combine monthly report files into one stream
Section titled “Example 6 — Combine monthly report files into one stream”Goal: The finance team exports one CSV per month to data/reports/. Report the rows and revenue per file and in total for the first half of 2024, with one stream over all six files.
Step 1 — List the files in order
Section titled “Step 1 — List the files in order”from pathlib import Path
report_paths = sorted(Path("data/reports").glob("2024-*.csv"))print([p.name for p in report_paths])['2024-01.csv', '2024-02.csv', '2024-03.csv', '2024-04.csv', '2024-05.csv', '2024-06.csv']sorted() gives the months in order, because YYYY-MM names sort as text in date order. Each Path is still only a name; no file is open yet.
Step 2 — Tag each row with its source file
Section titled “Step 2 — Tag each row with its source file”def tagged_rows(paths: list[Path]) -> Iterator[tuple[str, dict[str, str]]]: """Yield (file name, row) for every row of every file.""" for path in paths: with open(path, encoding="utf-8", newline="") as f: yield from ((path.name, row) for row in csv.DictReader(f))
name, row = next(tagged_rows(report_paths))print(name, row["order_id"], row["revenue"])2024-01.csv O006743 39.98yield from delegates to a generator expression that pairs each row with its file name. Keeping the source with each row is a common habit in data engineering: when a value looks wrong, you know which file to open.
Step 3 — Aggregate per file and in total
Section titled “Step 3 — Aggregate per file and in total”rows_per_file: Counter[str] = Counter()revenue_per_file: defaultdict[str, float] = defaultdict(float)for name, row in tagged_rows(report_paths): rows_per_file[name] += 1 revenue_per_file[name] += float(row["revenue"])for name, count in rows_per_file.items(): print(f"{name} {count:>3} {revenue_per_file[name]:>10,.2f}")total_rows = rows_per_file.total()total_revenue = sum(revenue_per_file.values())print(f"{'total':<11} {total_rows:>3} {total_revenue:>10,.2f}")2024-01.csv 48 14,162.332024-02.csv 48 4,719.042024-03.csv 47 12,296.722024-04.csv 52 10,879.042024-05.csv 47 6,675.862024-06.csv 55 8,533.40total 297 57,266.39The numbers match the data dictionary, including April, whose columns are in another order. DictReader finds revenue by name in every file.
Step 4 — The same stream with chain.from_iterable
Section titled “Step 4 — The same stream with chain.from_iterable”def read_csv(path: Path) -> Iterator[dict[str, str]]: with open(path, encoding="utf-8", newline="") as f: yield from csv.DictReader(f)
all_rows = chain.from_iterable(read_csv(p) for p in report_paths)print(sum(1 for _ in all_rows))297chain.from_iterable takes a stream of streams, here a generator of six file readers, and flattens it. The generator expression creates each reader only when chain needs it, so the files still open one at a time. Use this form when you already have a function that streams one file.
Common mistakes:
- Writing
chain(*[read_csv(p) for p in paths]). The list creates every generator up front. With generators that is cheap, but with eager readers it opens all files at once. Preferchain.from_iterablewith a generator expression. - Joining the files as raw text lines. The header of each file then appears as a data row, and April’s columns land in the wrong places.
- Forgetting
sorted()onglob(). The file order ofglobdepends on the operating system.
Example 7 — Fix a report that reads its stream twice
Section titled “Example 7 — Fix a report that reads its stream twice”Goal: A colleague’s script prints the line count, total and mean revenue of the Electronics lines. It prints a count of 0 and then crashes. Find the bug and fix it in two ways.
Step 1 — Run the broken report
Section titled “Step 1 — Run the broken report”electronics = ( s.revenue for s in parse_sales(read_rows("data/sales.csv")) if s.category == "Electronics")total = sum(electronics)count = sum(1 for _ in electronics)print(f"total {total:,.2f}, lines {count}")print(f"mean {total / count:.2f}")total 1,808,108.17, lines 0ZeroDivisionError: float division by zeroThe total is right. The count is 0, and the mean divides by 0. The first sum() exhausted the generator, so the second one counted an empty stream.
Step 2 — Fix it with one pass
Section titled “Step 2 — Fix it with one pass”total, count = 0.0, 0for s in parse_sales(read_rows("data/sales.csv")): if s.category == "Electronics": total += s.revenue count += 1print(f"total {total:,.2f}, lines {count}, mean {total / count:.2f}")total 1,808,108.17, lines 3942, mean 458.68One loop updates both results. The file is read once and memory stays constant. This is the best fix when you know all the results you need.
Step 3 — Fix it with a re-iterable source
Section titled “Step 3 — Fix it with a re-iterable source”class CategoryRevenue: """Re-iterable: each loop streams the file again."""
def __init__(self, path: str, category: str) -> None: self.path = path self.category = category
def __iter__(self) -> Iterator[float]: for s in parse_sales(read_rows(self.path)): if s.category == self.category: yield s.revenue
electronics = CategoryRevenue("data/sales.csv", "Electronics")total = sum(electronics)count = sum(1 for _ in electronics)print(f"total {total:,.2f}, lines {count}, max {max(electronics):,.2f}")total 1,808,108.17, lines 3942, max 5,196.00Each sum() and max() calls iter(), which runs __iter__ and creates a fresh generator, so the caller can use electronics like a list. The price is one full read of the file per pass, here three. Choose this fix when callers need several passes and the file is too big to keep.
Common mistakes:
- Fixing the bug with
tee(electronics). The firstsum()runs one copy to the end, soteestores all 3,942 values for the other copy. That is a list with extra steps. - Fixing the bug with
list(electronics)on a stream that can grow without limit. It works today and fails on next year’s file. - Making
__iter__returnselfin a class that should be re-iterable. That turns it back into a one-pass iterator.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
| Looping twice over one generator or iterator | Second loop gets nothing; sum() gives 0, max() raises ValueError |
One pass, re-create the stream, or a re-iterable class |
| Calling a generator function and expecting it to run | Nothing happens; no prints, no file read | Consume it: for, list(), sum(), next() |
len(gen) or gen[0] |
TypeError: object of type 'generator' has no len() |
Count with sum(1 for _ in gen); take items with next() or islice |
Opening the file in a with block outside the generator |
ValueError: I/O operation on closed file |
Open the file inside the source generator |
Peeking with next() and forgetting the item |
First row missing from the result | Put it back with chain([item], it) |
groupby on unsorted data |
The same key appears in several groups | Sort by the key first, or use a defaultdict |
Using a groupby group after moving on |
The old group is empty | Consume each group inside the loop |
Using the original iterator after tee |
Items vanish from the copies | Use only the copies |
One tee copy runs far ahead |
Memory grows like a list | Compute all results in one loop |
islice(a_list, n) in a loop to make chunks |
Every chunk is the first n items |
Call iter() once, then islice the iterator; or use batched |
| Returning a list from a pipeline stage | Memory grows with the file | Return a generator or a generator expression |
| Reading a side Counter before the sink runs | It is empty | Read side results after consuming the stream |
if value: for a missing-value check |
0.0 readings are dropped | if value is None: |
Raising StopIteration inside a generator |
RuntimeError: generator raised StopIteration |
Use return to end a generator |
The last row deserves a note. Inside a generator, a StopIteration that escapes, for example from a bare next() on an empty iterator, is turned into a RuntimeError (PEP 479). This keeps the bug from silently ending an outer loop. End a generator with return, and call next(it, None) when an iterator may be empty.
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web development: web frameworks stream large responses (CSV exports, server-sent events) from a generator, so the server never builds the whole response in memory. Django’s
StreamingHttpResponseand FastAPI’sStreamingResponseboth accept a generator. - Automation and DevOps: a log watcher reads a growing log file line by line (like
tail -f) and filters error lines with a generator pipeline. It runs for weeks in constant memory. - APIs: a client yields the items of a paginated API one by one and fetches the next page only when the consumer reaches the end of the current one (module 16).
- Tooling:
os.walk()andPath.rglob()are lazy, so a backup or lint tool can scan millions of files and stop at the first match.
Summary
Section titled “Summary”- An iterable gives an iterator with
iter(). An iterator gives items withnext()and raisesStopIterationat the end. Aforloop does this for you. - An iterator class has
__iter__(returnsself) and__next__. A re-iterable class returns a fresh iterator from__iter__, often by making__iter__a generator. - A function with
yieldreturns a generator. Its body runs lazily, from oneyieldto the next, and keeps its local state between calls.close()runs its cleanup. - A generator expression is a lazy list comprehension: constant memory, one pass. Use lists for small data you reuse.
yield fromdelegates to another iterable;chain.from_iterableflattens a stream of streams.- A lazy pipeline chains source → transforms → sink. One item is in flight at a time, so memory stays constant for any file size.
batchedgroups a stream into chunks for bulk work;islice,takewhile,dropwhile,groupbyandaccumulatework on sorted streams without loading them.teebuffers, so use it with care.- The
itertoolsdocs recipes (take,sliding_window,unique_everseen,first_trueand more) are small helpers built from these tools; themore-itertoolspackage ships them. - Every iterator is one-pass. Compute all results in one loop, re-create the stream, or wrap it in a re-iterable class.
Self-check questions
Section titled “Self-check questions”Q1. What is the difference between an iterable and an iterator? Give one example of each.
Answer
An iterable can give an iterator: iter(x) works on it. A list, a string and a dict are iterables. An iterator gives the items one by one with next() and remembers its position. A file object, csv.DictReader and a generator are iterators. Every iterator is also an iterable whose iter() returns itself, but a list is not an iterator.
Q2. You call gen = read_rows("data/sales.csv"), where read_rows is a generator function. Is the file open after this line?
Answer
No. Calling a generator function only creates the generator object. The body, including open(), starts at the first next() call.
Q3. What does this print?
def numbers(): print("a") yield 1 print("b") yield 2
g = numbers()print(next(g))print("c")print(next(g))Answer
a, 1, c, b, 2, each on its own line. The first next() runs the body up to yield 1. The caller then prints c. The second next() resumes after yield 1, prints b and stops at yield 2.
Q4. sys.getsizeof([x for x in range(10**6)]) is about 8 MB, but sys.getsizeof((x for x in range(10**6))) is about 200 bytes. Why? And why does the 8 MB still underestimate the list’s real memory?
Answer
The list stores a reference to each of the million values. The generator stores only its paused state: the current position in range and the expression to compute. getsizeof measures only the outer object, not the objects that it refers to, so the int objects in the list come on top of the 8 MB.
Q5. A script computes max(gen) and then sum(gen) on the same generator. What does sum return, and why is that dangerous?
Answer
0. max() exhausted the generator, so sum() sees an empty stream. No error is raised, so the wrong total can end up in a report. Compute both in one loop, or create the generator again.
Q6. When do you choose itertools.batched over a plain for loop over rows?
Answer
When the sink is faster or only works with groups: bulk database inserts with executemany, API calls that accept many records, writing one output file per chunk or reporting progress every N rows. Each chunk is a tuple of up to N items, and only one chunk is in memory at a time.
Q7. groupby(rows, key=lambda r: r["store_id"]) on data/sales.csv gives thousands of groups, not 12. Why, and what are the two fixes?
Answer
groupby groups only consecutive rows with the same key. The file is sorted by date, not by store, so the store changes almost every row. Either sort the rows by store_id first (which loads them), or use a defaultdict or Counter sink that accumulates per store in one pass.
Q8. What are the three caveats of itertools.tee?
Answer
- It buffers every item that one copy has consumed and another has not, so a copy that runs ahead makes the buffer grow up to the whole stream.
- You must not use the original iterator after the split, or the copies lose items.
- The copies are not thread-safe.
Q9. What does yield from csv.DictReader(f) do, and what is the equivalent loop?
Answer
It yields every row of the reader, one at a time, from the current generator. The equivalent is for row in csv.DictReader(f): yield row. yield from also forwards close(), throw() and send() to the inner generator.
Q10. Why must a cleaning stage that drops rows also count them?
Answer
Dropped rows are invisible in the output. Without a count, a bug that drops half the file looks like a smaller dataset, not like an error. A count lets you assert that kept plus dropped equals the input, and report what was removed.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 28 exercises with hints and full solutions, from the iteration protocol to streaming ETL jobs.
- Mini-project: build a streaming health report for the sensor log, with cleaning, rolling statistics and spike detection.
- Cheat sheet: the protocol, generator patterns, pipelines,
itertoolsand its documented recipes on one page. - Next module: 11. Decorators and context managers treats functions as objects and shows how
withandcontextlibmanage resources such as the files in your pipelines.