Iterators & generators
P29.iterators-generators.01 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Closures & first-class functions
Where next?
Later in Iterators & Generators
P29.iterators-generators.01 · Audience: Guest, IT/ML learner, Language professional · Prerequisites: Closures & first-class functions
Later in Iterators & Generators
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.
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 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.
Off by default. The mentor always gets your file; this only decides whether your own copy stays here. Copies live in this browser only - they do not follow you to another device, and clearing site data removes them.
Your 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.
Loading exercise…
Loading exercise…
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.
Loading your notes...