Iterators & Generators in Python
Chapter 26: Iterators & Generators
5 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Iterators: one item at a time
An iterable is something you can go through, and iter() gives you an iterator that hands out its items one at a time with next(), raising StopIteration when there are none left.
Generators: functions that pause with yield
A function with yield in it is a generator function: calling it gives a paused generator, and each next() runs it to the next yield, hands out that value, and pauses again.
Generator expressions and laziness
A generator expression, (x * x for x in nums), is a one-line generator that makes each value only when asked, instead of building the whole list first.
Pipelines: generators feeding generators
Generators can be chained into a pipeline, each taking items from the one before, doing one small job, and passing them on, one item at a time.
Your own iterator: __iter__ and __next__
for x in obj first calls iter(obj), which runs obj.iter() to get an iterator, then calls next() on it, which runs next(), again and again until next raises StopIteration. Write those two methods, and your own class works in a for loop.