Python Tutorial: Generators & Iterators
Process infinite sequences without running out of memory. yield changes everything.
Lazy values on demand
Lists hold all values in memory at once. What if you have a million records? Or an infinite stream?
Generators produce values one at a time, on demand. They use almost no memory and can even be infinite. Ten steps.
What you'll learn in this Python generators & iterators tutorial
This interactive Python tutorial has 7 hands-on exercises. Estimated time: 18 minutes.
- A million numbers — without the memory — What if you need to work with a million numbers? If you put them all in a list, you're using megabytes of RAM upfront — …
- yield — your first generator — `yield` turns a regular function into a generator. When Python hits `yield`, it:
- Write the Fibonacci generator — Here's where generators shine. The Fibonacci sequence is infinite — you can't put it in a list. But with a generator, yo…
- Generator expressions — one-line generators — Just like list comprehensions (`[x for x in ...]`) create lists, **generator expressions** (`(x for x in ...)`) create g…
- StopIteration — generator exhaustion — When a generator runs out of values, it raises `StopIteration`. The `for` loop handles this automatically — it's how the…
- yield from — delegate to another generator — `yield from` delegates to another iterable — it yields every value from that sub-generator before continuing.
- Build a generator pipeline — Generators compose beautifully — chain them to process data through stages, each stage lazy:
Python Generators & Iterators concepts covered
- Lazy values on demand