Iterators & generators
Write generators that process large data lazily.
By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.
In short
An iterator hands out values one at a time when asked with next(). Generators are the easy way to write iterators: a function with yield pauses after each value, so huge or endless data never has to sit in memory.
Think of it like this: A generator is a ticket dispenser: it prints the next ticket only when someone pulls.
Explained simply
When you write for x in something, Python does not grab everything at once. It asks the thing for a helper object called an iterator, then asks that helper "next, please" again and again until it says "I'm done". Lists, strings, dicts, files and ranges all support this.
A generator is the easiest way to make your own iterator. It looks like a normal function, but it uses yield instead of return. Each yield hands one value out and freezes the function in place. The next request wakes it up exactly where it stopped, with all its variables still there.
Why bother? Because a generator only holds one value at a time. Reading a 20 GB log file into a list would need 20 GB of memory. A generator that yields one line at a time needs about as much memory as one line, so it works even on a small laptop.
The catch is that iterators are one-way and single-use, like a tape that only plays forward. Once a generator has given out all its values, it is empty. If you need the data twice, either keep a list or call the generator function again to get a fresh one.
Press Play on a diagram to walk through it one step at a time.
- for loop to count_up(3): next()1next()
- count_up(3) to for loop: yield 1, then pause2yield 1, then pause
- for loop to count_up(3): next()3next()
- count_up(3) to for loop: yield 2, then pause4yield 2, then pause
- for loop to count_up(3): next()5next()
- count_up(3) to for loop: yield 3, then pause6yield 3, then pause
- for loop to count_up(3): next()7next()
- count_up(3) to for loop: StopIteration: loop ends8StopIteration: loop ends
- Builds everything now
- Memory grows with size
- len(), indexing, many passes
- Good for small or reused data
- Computes on demand
- Tiny, constant memory
- One pass, forward only
- Good for big data or early stop
- Reusable (fresh iterator each loop)
- list, tuple, str
- dict, set
- range
- Single-use (are iterators)
- generator
- open file
- map, filter, zip
- csv.reader
In depth
Iterable vs iterator: the protocol
An iterable is anything with an __iter__ method that returns an iterator. An iterator has a __next__ method that returns the next value or raises StopIteration, and its own __iter__ simply returns itself. A for loop is really: it = iter(obj), then call next(it) repeatedly, and stop quietly when StopIteration appears.
This split explains a lot of behaviour. A list is an iterable but not an iterator: each loop calls iter() and gets a fresh iterator, so you can loop over a list many times. A file object or a generator is its own iterator, so a second loop continues from where the first stopped, usually at the end. next(it, default) returns default instead of raising when the iterator is empty.
- iter([1, 2]) is not iter([1, 2]): two independent iterators
- iter(gen) is gen: a generator is its own iterator
- next(it, None) avoids StopIteration for an empty iterator
How a generator pauses and resumes
Calling a generator function runs none of its body. It just creates a generator object in the created state. The first next() runs the code up to the first yield, hands out that value and suspends: the local variables and the current line are saved. Each later next() resumes on the line after the yield.
When the function body finishes or reaches return, the generator raises StopIteration and becomes closed. A return value inside a generator is attached to that StopIteration, and yield from passes it back to the outer generator. You can watch the states with inspect.getgeneratorstate(gen), which returns GEN_CREATED, GEN_RUNNING, GEN_SUSPENDED or GEN_CLOSED. gen.close() ends a suspended generator early and still runs its finally blocks, so cleanup code is safe.
- Step 1GEN_CREATED
gen = f(): no code has run yet
- Step 2GEN_RUNNING
next(gen): runs until the next yield
- Step 3GEN_SUSPENDED
Paused at yield; locals kept
- Step 4GEN_CLOSED
Body ended, return, or gen.close()
Generator expressions and memory
A list comprehension [x * x for x in range(1_000_000)] builds the full list right away; just the list's slots for a million items take about 8 MB on a 64-bit machine, before counting the numbers themselves. The generator expression (x * x for x in range(1_000_000)) is a small object of a couple of hundred bytes that computes one value per request. When it is the only argument to a function, you can drop the extra parentheses: sum(x * x for x in nums).
Use a list when you need len(), indexing, slicing, sorting or more than one pass. Use a generator when you will consume the values once, in order, especially if the data is large or the consumer may stop early, like any(), next() or islice(). Many built-ins accept any iterable, so passing a generator to sum, min, max, any, all, sorted, set, dict or str.join just works.
Pipelines: chaining generators
Generators combine like pipes on the command line. One generator reads lines, the next parses each line into a record, the next filters records, and the last step consumes the result. Each stage pulls one item from the stage before it, so only one record is in flight at a time, no matter how big the input is.
yield from other_iterable inside a generator hands out every item of another iterable, which keeps stage functions short. The pipeline is lazy: building it does nothing; work starts only when the final consumer asks for values. That also means a consumer that stops early, like islice(pipeline, 5), stops the whole chain early, so you only read as much of the file as needed.
- Step 1read_lines(path)
Yields raw lines from the file
- Step 2parse(lines)
Yields a dict per line
- Step 3errors(records)
Yields only level == ERROR
- Step 4islice(..., 5)
Stops after 5, so reading stops too
Large files: what really happens, and one trap
for line in f reads the file through a buffer (usually several kilobytes), splitting it into lines as you go, so memory stays flat. f.read() and f.readlines() load the whole file, so avoid them for big data. csv.reader and csv.DictReader are lazy too, yielding one row at a time.
The trap is closing the file too early. If a function opens a file in a with block and returns a generator expression over it, the with block closes the file on return, and the first next() fails with ValueError: I/O operation on closed file. Put the with block inside a generator function (with yield) instead. Then the file stays open while the caller iterates and closes when the generator finishes or is closed.
- Good: def rows(p): with open(p) as f: yield from f
- Bad: def rows(p): with open(p) as f: return (l for l in f)
- Count lines cheaply: sum(1 for _ in open(path))
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Understand the iterator protocol~45m
- 2Write generator functions with yield~45m
- 3Use generator expressions~45m
- 4Process a large file lazily~45m
Key points
- iter(x) gets an iterator; next(it) gets the next value or raises StopIteration.
- A function containing yield returns a generator instead of running immediately.
- Generator expressions use parentheses: (x * x for x in nums).
- Generators are single-use: once exhausted, they yield nothing more.
- Looping over a file with a generator processes gigabytes using little memory.
Key terms
Tap a card to flip it. 0/5 known
Examples
def read_errors(path):
with open(path, encoding="utf-8") as f:
for line in f:
if "ERROR" in line:
yield line.rstrip()
def count_up(n):
for i in range(1, n + 1):
yield i
print(list(count_up(3))) # [1, 2, 3]
print(sum(x * x for x in range(1000))) # no list built
gen = count_up(2)
print(next(gen), next(gen)) # 1 2A hand-written iterator class
To see the protocol without any magic, write it yourself. Step 1: __iter__ returns self, because the object is its own iterator. Step 2: __next__ returns the next number or raises StopIteration when it reaches zero. Step 3: list() drives it to the end. Step 4: a second list() gets nothing, because the iterator is used up. A generator function does all of this in four lines.
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
c = Countdown(3)
print(list(c)) # [3, 2, 1]
print(list(c)) # []: the iterator is used upFirst five errors from a huge log
app.log may be gigabytes in size. Step 1: read_lines yields lines from inside the with block, so the file stays open while we iterate. Step 2: parse turns each line into a dict. Step 3: errors filters with a generator expression. Step 4: islice takes five results. Because everything is lazy, Python reads only until the fifth error is found, then stops.
from itertools import islice
def read_lines(path):
with open(path, encoding="utf-8") as f:
yield from f
def parse(lines):
for line in lines:
ts, level, msg = line.rstrip("\n").split(" ", 2)
yield {"ts": ts, "level": level, "msg": msg}
def errors(records):
return (r for r in records if r["level"] == "ERROR")
first5 = list(islice(errors(parse(read_lines("app.log"))), 5))Quick reference
- A for loop is it = iter(obj) plus next(it) until StopIteration
- next(it, default) returns default instead of raising when empty
- Calling a generator function runs nothing until the first next()
- sum(x * x for x in nums): a lone generator argument needs no extra parentheses
- yield from iterable hands out every item of another iterable
- Keep the with block inside the generator, or the file closes too early
- Need the data twice? Use a list, or call the generator function again
Common mistakes
- Looping over the same generator twice and getting nothing the second time.
- Calling list() on a huge generator and losing the memory benefit.
- Expecting a generator function's body to run before the first next().
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a generator evens(limit) that yields 0, 2, 4, ... up to and including limit if it is even. Print list(evens(10)).
- Exercise 2medium
Write chunked(iterable, size) that yields lists of up to size items, with the last list possibly shorter. It must work on generators, not just lists.
- Exercise 3hard
An access log has the client IP as the first word of each line. Find the 3 busiest IPs in a file of any size, using generators so memory stays small, and skip blank lines.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between yield and return?
- return ends the function and sends back one value. yield sends back a value and pauses, so the function can continue and produce more values later.
- Can I get the length of a generator?
- Not without consuming it. sum(1 for _ in gen) counts the items, but afterwards the generator is empty.
- Is a generator faster than a list?
- Not always. For small data a list can be a little faster. Generators win on memory and when you can stop early.
- How do I restart a generator?
- You can't rewind one. Call the generator function again to get a new generator that starts from the beginning.