Iterators & Generators
The iteration protocol, iterables vs iterators, writing generators with yield, generator expressions, lazy pipelines, yield from, send/close, itertools recipes, and generator-based context managers.
for loops, comprehensions, sum(), unpacking, in — all of them work through one small protocol. Understanding it lets you write memory-efficient, lazy code that processes millions of items (or infinite streams) one at a time.
The iteration protocol
- An iterable has
__iter__(), which returns an iterator. Lists, strings, dicts, sets, files and ranges are iterables. - An iterator has
__next__(), which returns the next item or raisesStopIteration, and__iter__()returning itself.
A for loop is roughly:
it = iter(items) # calls items.__iter__()
while True:
try:
x = next(it) # calls it.__next__()
except StopIteration:
break
body(x)Iterables can be looped over many times (each iter() returns a fresh iterator). Iterators are single-use: once exhausted, they stay empty.
nums = [1, 2, 3]
it = iter(nums)
list(it) # [1, 2, 3]
list(it) # [] — exhaustedA hand-written iterator
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
list(Countdown(3)) # [3, 2, 1]That's a lot of boilerplate for a simple idea — which is why generators exist.
Generators
A function containing yield is a generator function. Calling it doesn't run the body; it returns a generator object (an iterator). Each next() runs the body until the next yield, hands out the value, and freezes the function — local variables and position intact — until the next request.
def countdown(start):
while start > 0:
yield start
start -= 1
gen = countdown(3)
next(gen) # 3
next(gen) # 2
list(gen) # [1]Under the hood, the generator's frame lives on the heap and is resumed on each next() — making generators cheap coroutines.
Generator expressions
Like list comprehensions but lazy — parentheses instead of brackets:
squares_list = [x * x for x in range(10_000_000)] # builds a list: ~400 MB
squares_gen = (x * x for x in range(10_000_000)) # ~200 bytes; computes on demand
total = sum(x * x for x in range(10_000_000)) # parentheses optional as the sole argumentLazy pipelines
Chain generators to build streaming data pipelines with constant memory:
def read_lines(path):
with open(path, encoding="utf-8") as f:
for line in f: # files are lazy iterators too
yield line.rstrip("\n")
def parse(lines):
for line in lines:
ip, _, _, ts, req, status, size = line.split(" ", 6)
yield {"ip": ip, "status": int(status), "size": int(size)}
def errors(records):
return (r for r in records if r["status"] >= 500)
top = Counter(r["ip"] for r in errors(parse(read_lines("access.log"))))Each record flows through all stages before the next is read — a 50 GB log uses the same memory as a 50 KB one.
Infinite sequences
from itertools import count, islice, cycle
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
list(islice(fibonacci(), 10)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
ids = count(1000) # 1000, 1001, 1002, …
next(ids)yield from
Delegate to a sub-iterator (and receive its return value):
def flatten(nested):
for item in nested:
if isinstance(item, list):
yield from flatten(item) # recursive generators
else:
yield item
list(flatten([1, [2, [3, 4]], 5])) # [1, 2, 3, 4, 5]
def walk_tree(node):
if node:
yield from walk_tree(node.left)
yield node.value
yield from walk_tree(node.right)send, throw and close
Generators are two-way: gen.send(value) resumes the generator and makes the paused yield expression evaluate to value. This was the foundation of Python's coroutines before async/await.
def running_average():
total = count = 0
average = None
while True:
value = yield average # receive a value, emit the current average
total += value
count += 1
average = total / count
avg = running_average()
next(avg) # prime it: advance to the first yield
avg.send(10) # 10.0
avg.send(20) # 15.0
avg.close() # raises GeneratorExit inside; finally blocks runA return value inside a generator sets StopIteration.value (what yield from returns).
itertools: the iterator toolbox
| Function | Does | Example |
|---|---|---|
chain(a, b) | Concatenate iterables | chain(list1, list2) |
islice(it, n) | Slice an iterator | First n items |
groupby(it, key) | Group consecutive equal keys (sort first!) | Group log lines by date |
accumulate(it) | Running totals | Prefix sums |
pairwise(it) | Overlapping pairs (3.10+) | Differences between neighbours |
batched(it, n) | Chunks of n (3.12+) | Batch database inserts |
product, permutations, combinations | Combinatorics | Brute-force search |
takewhile, dropwhile, filterfalse | Conditional slicing | |
tee(it, n) | n independent iterators from one | Use sparingly (buffers) |
zip_longest | Zip, padding the shorter |
from itertools import groupby, pairwise, batched, accumulate
for day, entries in groupby(sorted(logs, key=lambda e: e.day), key=lambda e: e.day):
print(day, sum(1 for _ in entries))
deltas = [b - a for a, b in pairwise(prices)]
for chunk in batched(rows, 500):
db.insert_many(chunk)
list(accumulate([1, 2, 3, 4])) # [1, 3, 6, 10]When to use generators
- Processing large files, database cursors or API pages item by item.
- Building pipelines of transformations.
- Representing infinite or expensive-to-compute sequences.
- Writing custom iteration for your own data structures (
__iter__as a generator). - Not when you need random access,
len(), or multiple passes — materialise a list then.
- Iterables produce iterators via iter; iterators produce values via next until StopIteration.
- Generator functions (yield) create iterators that pause and resume, keeping local state.
- Generator expressions are lazy comprehensions: constant memory.
- Chain generators into streaming pipelines; use yield from to delegate.
- itertools provides fast building blocks: chain, islice, groupby, pairwise, batched, accumulate.
QWhat is the difference between an iterable and an iterator?easy
An iterable is any object with iter that returns a new iterator, such as a list; it can be iterated many times. An iterator has next to produce the next value (raising StopIteration at the end) and iter returning itself; it keeps position state and is exhausted after one pass.
QWhy use a generator instead of returning a list?easy
A generator computes values lazily, one at a time, so memory stays constant regardless of the number of items, results can start being consumed before all are computed, infinite sequences are possible, and work stops early if the consumer stops. A list is better when you need random access, length, or multiple passes.