Explain it simply
Explain it simply
A restaurant can cook all ten dishes at once and cover the table with them, or cook each dish only when a guest orders it. The first way takes a lot of space and may waste food nobody eats. The second does only the work that is needed, at the moment it is needed.
A list is the first way: every element sits in memory at once. A generator is the second: it computes a value only when you ask for the next one, then remembers where it stopped and waits until you ask again.
Problem → Why → Solution
The problem: building everything in memory first
Say you want the error lines from a huge log file. The function below collects millions of lines into a list before returning anything. The caller only wants the first error, yet has to wait for the entire file to be read. If the file is larger than the available RAM, the program can die with a MemoryError.
def error_lines(path):
found = []
with open(path) as f:
for line in f:
if "ERROR" in line:
found.append(line) # every match is kept in memory
return found # nothing reaches the caller until the end
first = error_lines("server.log")[0] # read 5 GB to use one lineWhy is this wasted work?
return ends the function once and must hand back everything in one go, so all results have to be gathered first. yield hands back one value and pauses the function instead. Replace append(line) with yield line and the caller receives the first error immediately and reads only as far as it needs.
Core concept: a function that pauses and resumes
As soon as a function body contains the yield keyword, it becomes a generator function. The key fact is that calling it, as in countdown(3), runs none of the body. Python only returns a generator object, which is like a paused function call: it holds the local variables and the position the code has reached.
Calling next(gen) runs the body from where it paused up to the next yield. yield n hands n to the caller and stops right there. The next call to next() resumes on the line after the yield, and because changes such as n -= 1 were kept, it continues from the previous state. When the body reaches its end or a return statement, next() raises the StopIteration exception to signal that there are no more values.
A for loop handles this protocol for you. Behind the scenes, for value in gen: calls next() again and again, catches StopIteration and ends the loop quietly. Functions such as list(), sum() and max() consume iterables the same way. Generators are iterators, so they are single-use: once one is exhausted, getting the values again means calling the generator function to create a fresh object.
Thanks to this lazy evaluation, a generator keeps roughly one value in memory at a time, and its size barely changes however long the sequence is. You can even write an endless generator with while True, because the caller only takes as many values as it needs. A generator expression is the short form of this: swap a list comprehension's [ ] for ( ) and (x * x for x in data) returns a generator instead of building a list.
- Calling it gives a paused object
- next() runs to the next yield
- yield hands out a value and pauses
- End of body raises StopIteration
Local variables survive between yields, which is what lets the function resume where it stopped.
General pattern
def produce(source):
for item in source:
yield transform(item) # hand out one value, then pause
gen = produce(data) # nothing has run yet
first = next(gen) # run up to the first yield
for value in gen: # keep calling next() until StopIteration
use(value)
lazy = (expression for item in iterable if condition)Calling a function that contains yield gives a generator object. next() takes one value at a time and a for loop takes the rest. The last line is a generator expression, written with parentheses.
Example: tracing exactly when a generator runs
The countdown generator prints a line at its start and at its end, so you can see when the body really runs. Watch where the indented "(...)" lines appear in the output; their position is the evidence of lazy evaluation.
def countdown(n):
print(f" (countdown starts at {n})")
while n > 0:
yield n
n -= 1
print(" (countdown finished)")
gen = countdown(3)
print("1. created:", type(gen).__name__)
print("2. first next():", next(gen))
print("3. second next():", next(gen))
print("4. the rest:", list(gen))
print("5. used up:", list(gen))
try:
next(gen)
except StopIteration:
print("6. next() on a finished generator raises StopIteration")
def naturals():
n = 1
while True:
yield n
n += 1
numbers = naturals()
print("7. first five:", [next(numbers) for _ in range(5)])
print("8. it remembers:", next(numbers))
squares = (x * x for x in range(1, 6))
print("9. sum of squares:", sum(squares))Code breakdown
- Line 9-10
gen = countdown(3)countdown(3) is called, yet "(countdown starts at 3)" has not appeared. The first output line is "1. created: generator", which proves the body has not run at all.
- Line 11
print("2. first next():", next(gen))Only on the first next() does the body start: it prints the start line, reaches yield n, hands out 3 and pauses. That is why "(countdown starts at 3)" appears just above the "2." line.
- Line 13
print("4. the rest:", list(gen))list() keeps calling next() until StopIteration. After taking 1, the while loop ends, "(countdown finished)" is printed and the function returns. Only [1] is left because 3 and 2 were already taken.
- Line 14-19
print("5. used up:", list(gen))Calling list() on an exhausted generator raises no error; it simply gives []. Calling next() directly does raise StopIteration, which the try/except catches.
- Line 22-31
while True:naturals() never ends, but the caller asks for only five values, so nothing hangs. The next next() returns 6 because n is remembered between yields.
- Line 33-34
squares = (x * x for x in range(1, 6))The parentheses make this a generator expression, not a list. sum() pulls the values one at a time: 1 + 4 + 9 + 16 + 25 = 55.
1. created: generator
(countdown starts at 3)
2. first next(): 3
3. second next(): 2
(countdown finished)
4. the rest: [1]
5. used up: []
6. next() on a finished generator raises StopIteration
7. first five: [1, 2, 3, 4, 5]
8. it remembers: 6
9. sum of squares: 55Behind the for loop: iter() and next()
Python's iteration protocol has two parts. An iterable, such as a list, string or dict, is an object that returns an iterator when you call iter() on it. An iterator is an object that returns the next value from next() and raises StopIteration when it runs out. A list is iterable but not an iterator, so you can loop over it twice: each loop asks for a fresh iterator. A generator is itself an iterator, with iter(gen) is gen, so it can be looped over only once.
| List | Generator | |
|---|---|---|
| When values are computed | All at creation | One per next() call |
| Memory | Grows with the element count | Small and nearly constant |
| Loop over it twice | Yes | No, create a new one |
| len() and [0] indexing | Supported | TypeError |
import sys
as_list = [n * 2 for n in range(1_000_000)]
as_gen = (n * 2 for n in range(1_000_000))
# Exact byte counts depend on the Python version and platform
print("list bytes:", sys.getsizeof(as_list)) # millions of bytes
print("generator bytes:", sys.getsizeof(as_gen)) # a few hundred bytes
print(sum(as_gen) == sum(as_list)) # same values: TrueIn real projects
Where this shows up in real projects
Python's file objects are themselves lazy iterators: for line in open(path): reads one line at a time without loading the whole file. Combine that with a generator and you can process gigabyte-sized logs, CSV exports and data dumps even on a small laptop. range(), dict.items(), zip() and map() also produce values on demand instead of building lists.
When an API returns data in pages, a generator can request one page at a time and yield the items one by one, so the caller writes an ordinary for loop without knowing pages exist. ORM methods such as Django's QuerySet.iterator() read database rows in batches, and generator expressions like sum(order.total for order in orders) compute aggregates without building an intermediate list. When you need to loop over the data twice or need len(), a list is still the better fit.
Common mistakes
Common mistakes
1. Looping over a generator twice
With scores = (s for s in data), calling max(scores) and then min(scores) fails: the first call exhausts the generator, so min() raises ValueError: "min() iterable argument is empty". With a second for loop it is harder to spot, because the loop silently does nothing. If you need the values twice, store them with list().
2. Assuming that calling it runs the body
If save_all(rows) contains a yield, calling save_all(rows) saves nothing: you get a generator object and throw it away. Do not put yield in a function you call for its side effects, or actually iterate it with a for loop or list().
3. Using list operations such as indexing and len()
gen[0] raises "'generator' object is not subscriptable" and len(gen) raises "object of type 'generator' has no len()". To get just the first value use next(gen), and pass a default like next(gen, None) if it might be empty.
4. Calling list() on an endless generator
list(naturals()) never sees StopIteration, so it runs until memory is exhausted. Take only what you need from an endless generator by using break inside a loop or by calling next() a fixed number of times.
Mini challenge
Mini challenge: a batching generator
Write a chunked(items, size) generator that yields lists of up to size items from any iterable. It is the pattern used to insert rows into a database in groups or to send batched API requests.
- Raise ValueError when size is less than 1
- The last batch may be smaller than size but must not be dropped
- Never collect all items up front; hold only one batch at a time
- Take the first batch with next() and print the sizes of the rest
def chunked(items, size):
# TODO: reject a size below 1 with ValueError
# TODO: fill a batch list item by item
# TODO: yield the batch when it is full, then start a new one
# TODO: after the loop, yield a final partial batch if one is left
...
# TODO: print list(chunked(range(7), 3)), list(chunked("abcd", 2)), list(chunked([], 3))
# TODO: batches = chunked(range(1, 11), 4); print next(batches), then remaining sizes
# TODO: print the total of the even numbers 1..10 with a generator expressionExpected: [[0, 1, 2], [3, 4, 5], [6]] [['a', 'b'], ['c', 'd']] [] first batch: [1, 2, 3, 4] batch sizes left: [4, 2] total of evens: 30
Show hint
Start with batch = [] and append each item. When len(batch) == size, yield batch and then start a new list with batch = [] (do not call clear() on the old one, because that would also empty the list you just yielded).
Show solution
def chunked(items, size):
if size < 1:
raise ValueError("size must be at least 1")
batch = []
for item in items:
batch.append(item)
if len(batch) == size:
yield batch
batch = []
if batch:
yield batch
print(list(chunked(range(7), 3)))
print(list(chunked("abcd", 2)))
print(list(chunked([], 3)))
batches = chunked(range(1, 11), 4)
print("first batch:", next(batches))
print("batch sizes left:", [len(b) for b in batches])
print("total of evens:", sum(n for n in range(1, 11) if n % 2 == 0))Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Calling a function that contains yield returns a generator object and runs none of the body.
- Each next() runs to the following yield and keeps local state exactly where it paused.
- The end of the body raises StopIteration, which for loops handle for you; a generator is single-use.
- A generator expression (expr for x in data) builds no list, so large and endless sequences stay cheap in memory.
Python Documentation — Functional Programming HOWTO — Python Software Foundation