Generators & Lazy Iteration
Lesson 1 of 6 · View course roadmap
Learn the idea
A generator is a function that produces values one at a time instead of building a whole list in memory. Swap return for yield and Python gives you a pausable function:
yield value— hands one value to the caller and freezes the function right there, local variables intactnext(gen)— resumes execution until the nextyield- A
forloop callsnext()for you until the generator is exhausted
This is lazy evaluation: values are computed only when asked for. A generator over a 10 GB log file uses a few kilobytes of memory, because only one line exists at a time.
Generator expressions look like list comprehensions with round brackets: (n * n for n in range(10**9)) is created instantly — nothing is computed until you iterate.
Where you'll use this
Generators are how Python streams anything bigger than RAM: Django querysets, csv.reader, database cursors and every line-by-line log processor are lazy iterators. Data engineers chain generators into pipelines that crunch terabytes on a laptop.
Common mistakes
- A generator is exhausted after one pass — looping over it a second time silently yields nothing. Recreate it or store the results if you need them twice.
- Calling a generator function doesn't run any of its code:
countdown(3)returns a generator object; the body only runs when you iterate. - Using
len()on a generator → TypeError. A lazy stream has no length until it's consumed.
Pro tip
yield from delegates to another iterable in one line: def walk(tree): yield from tree.left; yield tree.value; yield from tree.right. It's the secret to elegant recursive generators.
Try it yourself
The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.
Output appears here…
Pass the challenge +40 XP
Write a generator function countdown(n) that yields the numbers from n down to 1. Loop over countdown(3) printing each value on its own line, then print Liftoff!.
3 2 1 Liftoff!
Use a while loop inside the generator: while n > 0: yield n; n -= 1. Then: for value in countdown(3): print(value).
def countdown(n):
while n > 0:
yield n
n -= 1
for value in countdown(3):
print(value)
print("Liftoff!")
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.