Python - Iterators & Generators
Overview
Estimated time: 35–45 minutes
Understand the iteration protocol (iter/next), build generator functions with yield
, and use generator expressions for efficient pipelines.
Learning Objectives
- Explain iterable vs iterator and how
for
loops work under the hood. - Write generator functions and generator expressions.
- Know when generators improve memory and readability.
Prerequisites
Iteration protocol
xs = [1, 2, 3]
it = iter(xs)
print(next(it))
print(next(it))
print(next(it))
# next(it) # StopIteration
Expected Output:
1\n2\n3
Generator function
def count_up(n):
i = 1
while i <= n:
yield i
i += 1
for v in count_up(3):
print(v)
Expected Output:
1\n2\n3
Generator expression
total = sum(x*x for x in range(5))
print(total)
Expected Output: 30
Common Pitfalls
- Exhausting an iterator/generator and then expecting it to produce values again.
- Using list when a generator would avoid building large intermediate results.
Checks for Understanding
- What exception ends an iterator?
- When might a generator help with memory usage?
Show answers
StopIteration
- When processing large or streaming datasets where you can consume values lazily.
Exercises
- Write a generator that yields even numbers up to N.
- Use a generator expression to compute the sum of cubes from 1..N.