Learn: Iterators and generators¶
Four notebooks, in order. Each is self-contained but they build on each other — if you work through them in sequence you'll cover the whole topic once.
Notebooks in this section¶
- The iteration protocol — what actually happens when you write a
forloop.iter(),next(),StopIteration, and why any object with these behaviours fits into Python's iteration machinery. - Generator functions — the
yieldkeyword. How generator functions turn sequential code into iterables, pausing between values instead of computing them all at once. - Generator expressions and
itertools— inline generator syntax ((x*2 for x in xs)) and the standard-library toolkit of iterator combinators. - Custom iterators — writing iterator classes when a generator function isn't the right shape. The
__iter__/__next__pair and when you'd reach for them.
After these, the Recipes cover task-focused applications and the Reference has quick lookups for the iterator protocol, generator syntax, and itertools.