Python 3D Academyবাংলা

Iterators & Generators in Python

Chapter 26: Iterators & Generators

5 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.