Python generators and iterators, explained with real examples
How iteration works under the hood, how yield turns a function into a lazy generator, how pipelines process files bigger than memory, and the exhaustion trap that catches everyone.
Generators are one of those features you can ignore for a while and then suddenly need everywhere: reading a log file with ten million lines, streaming rows from a database, chaining processing steps without building huge lists in between.
What a for loop really does
for line in lines:
print(line)Under the hood, Python calls iter(lines) once to get an iterator, then next() on it again
and again until it raises StopIteration:
it = iter(lines)
while True:
try:
line = next(it)
except StopIteration:
break
print(line)Lists, strings, dicts, files and range are all iterable: they can hand out an iterator.
yield: a function that pauses
def countdown(n):
while n > 0:
yield n
n -= 1
for x in countdown(3):
print(x) # 3, 2, 1Calling countdown(3) runs none of its body. It returns a generator object. Each next()
runs the body until the next yield, hands out the value, and freezes, local variables and all,
until it's asked again.
Why lazy matters
def read_events(lines):
for line in lines:
line = line.strip()
if line and not line.startswith("#"):
yield parse_event(line)Give this a file object and it reads one line at a time. Memory use stays flat whether the file has a hundred lines or a hundred million. That's exactly how the tracking service in the Python Developer career path reads scanner exports.
Pipelines
Generators chain nicely, each stage pulling from the one before:
import itertools
with open("scans.txt") as f:
events = read_events(f)
delivered = (e for e in events if e.status == "delivered")
first_ten = itertools.islice(delivered, 10)
for event in first_ten:
print(event)Nothing is read until the for loop asks for the first item, and reading stops after the tenth
match. The parentheses version, (e for e in ...), is a generator expression: like a list
comprehension, but lazy.
The exhaustion trap
squares = (n * n for n in range(4))
print(sum(squares)) # 14
print(sum(squares)) # 0A generator is used up after one pass. This bites when you pass a generator to a function that loops twice (once to count, once to process). If you need the data twice, store it in a list, or make the function loop once.
Useful tools
next(gen, default): the next item, ordefaultinstead of an exception.next((r for r in routes if r.fits(x)), None)finds the first match and stops.any()andall()stop as soon as they know the answer, so they pair well with generators.itertools:islice,chain,groupby,batched(3.12) and more.yield from other(): delegate to another generator.
When not to use one
If the data is small and you'll use it several times, a list is simpler and easier to debug. Reach for generators when the data is big, potentially infinite, or produced step by step. For the cost side of that decision, see complexity in practice.
Questions and answers
- What is the difference between an iterator and a generator in Python?
- An iterator is any object with __next__ (and __iter__ returning itself). A generator is the easiest way to make one: a function containing yield. Every generator is an iterator; not every iterator is a generator.
- Why can I only loop over a generator once?
- A generator produces values on demand and doesn't store them. Once it has yielded its last value it's exhausted, and looping again gives nothing. Create a new generator, or store the values in a list if you need them twice.
Practise it
Read next
- Python decorators explained: from @ syntax to retry and caching
What a decorator really is, how to write one with functools.wraps, decorators that take arguments like @retry(3), and when lru_cache helps or quietly serves stale data.
- Python context managers: how with works, and how to write your own
What the with statement guarantees, __enter__ and __exit__ step by step, the contextlib shortcut, and why returning True from __exit__ silently swallows errors.
- Reading files and CSV in Python: paths, encodings and DictReader
Open files safely with pathlib and with, choose the right encoding, handle Excel's byte order mark and decimal commas, and read CSV exports with csv.DictReader.
- Big-O in practice: amortised cost, worst cases and memory
What Big-O tells you on the job: the costs of common operations, amortised O(1), inputs that trigger the worst case, memory as a cost, and when to measure instead of guessing.