Iterators & generators
P29.iterators-generators.01 · Audience: guest, it-ml, language-pro · Prerequisites: Closures & first-class functions
Every for loop in Python runs on one small protocol — and once you can
build that protocol by hand, yield turns it from boilerplate into a
one-word superpower. This module rebuilds iteration from the bottom:
protocol, generators, laziness, and the itertools-style pipelines that
process streams you could never fit in memory.
ⓘ Concept: What a for-loop actually does
for loop calls iter(xs) once to get an iterator, then next() repeatedly until the iterator raises StopIteration. An object joins the protocol by implementing __iter__ (usually return self) and __next__ (return the next value, or raise StopIteration — and keep raising once exhausted).Why it matters — for x in xs desugars to iter() once, then next() until StopIteration — knowing the machinery lets you make any object loopable and demystifies every 'is it iterable?' bug.
Ask the mentor about this module
Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.
🎓 Practice ladder
3 graded rungs · ~32 minYour turn: rebuild the protocol with a Countdown class, swap
the boilerplate for a lazy paginate generator, then ship a
sliding_window that survives an infinite stream.
Rung 1 — rebuild the iterator protocol
Loading exercise…
Rung 2 — a lazy paginator with yield
Loading exercise…
Rung 3 — a sliding window over any stream
Loading exercise…
By the end, "make it lazy" should be a refactor you can do on sight: class-with-state to generator, list-building loop to yielding pipeline.
Where next?
Later in Iterators & Generators