Generator Functions
yield
Learn to write lazy, memory-efficient Python functions that produce values one at a time using the yield keyword.
What Is a Generator?
A generator is a special kind of function that returns an iterator. Instead of computing all values at once and storing them in memory, a generator produces values one at a time, pausing between each one.
Any function that contains the keyword yield (instead of or alongside return) is automatically a generator function.
Why Generators Matter
yield vs return
The Core Rule
The Generator Protocol
Generator vs List
| Generator | List | |
|---|---|---|
| Memory | \(O(1)\): one item at a time | \(O(n)\): all items stored |
| Evaluation | Lazy (on demand) | Eager (all at once) |
| Reusable? | No: single pass only | Yes: iterate many times |
| Indexing | No: sequential access | Yes: random access |
| Syntax | yield or ( ... ) | return or [ ... ] |
How to Write a Generator
Example 1: Countdown
Example 2: Fibonacci Sequence
Example 3: Generator Expressions
Python offers a shorthand for simple generators that mirrors list comprehension syntax, using parentheses instead of brackets.
Chaining Generator Pipelines
Delegating with yield from
yield from lets one generator delegate to another, forwarding all yielded values automatically.
State Preservation
Common Mistakes
Quick Reference Summary
| Concept | Syntax / Detail |
|---|---|
| Define generator | def func(): yield value |
| Create object | gen = func() |
| Get next value | next(gen) |
| Iterate all | for x in gen: ... |
| Delegate | yield from iterable |
| Gen expression | (expr for x in iterable) |
| Exhaustion | Raises StopIteration |
Question 1 of 5
What does calling a generator function (e.g., my_gen()) return?
Question 2 of 5
What happens when you call next() on a generator that has no more yield statements to execute?
Question 3 of 5
Consider this code:
def nums():
yield 10
yield 20
yield 30
g = nums()
next(g)
next(g)
result = next(g)
What is the value of result?
Question 4 of 5
Which syntax creates a generator expression?
Question 5 of 5
Consider this code:
def letters():
yield "a"
yield "b"
g = letters()
print(list(g)) # Line A
print(list(g)) # Line B
What does Line B print?