Caffeinated Coder
Book an appointment
Lesson 21 · Idiomatic Python

Iterators and generators

Every for loop in Python is driven by an iterator: an object that hands out one value per next() call and raises StopIteration when it has no more. A generator is the easiest way to write one: a function with yield in it. Step through countdown.py and watch the generator pause after each yield, keep its local n and its place, carry on exactly where it stopped on the next call, and finish with StopIteration, which the for loop catches quietly.

14 min9 steps5 questionsBeginner
Fig 21 · Interactive
Loading figure…
or ← →

Quiz Unlocks after the last step.