Iterables, iterators and generators

What a for loop actually calls, and why the repository's MyRange can only be used once.

What you'll learn
  • Distinguish an iterable from an iterator
  • Implement the iterator protocol with __iter__ and __next__
  • Write a generator and know when one is the better tool

b_iterable_and_loops1.py loops over a list, a tuple, a string, a dict, a set, a generator, range, enumerate and a file. They all work for the same reason: each is an iterable, an object whose __iter__ method returns an iterator, and an iterator is anything with a __next__ method that returns the next value or raises StopIteration.

A for loop is shorthand for exactly that protocol, which the second script spells out by hand:

iterator = iter(my_range)
while True:
    try:
        num = next(iterator)
        print(num)
    except StopIteration:
        break

Building one: MyRange

class MyRange:
    def __init__(self, start, end, step=1):
        self.start, self.end, self.step = start, end, step
        self.current = start
    def __iter__(self):
        return self
    def __next__(self):
        if self.step > 0 and self.current >= self.end:
            raise StopIteration
        ...
        result = self.current
        self.current += self.step
        return result

MyRange(1, 10, 2) yields 1, 3, 5, 7, 9 in a loop, a comprehension, list() and map. Notice that the script creates a fresh MyRange before every use. That is not an accident: because __iter__ returns self, the object is its own iterator, and the position current lives on it. Once exhausted, it stays exhausted:

r = MyRange(1, 10, 2)
list(r)   # [1, 3, 5, 7, 9]
list(r)   # []

The built-in range does not behave like this, because range is an iterable whose __iter__ returns a new iterator each time. To fix MyRange, keep the start in the object and make __iter__ a generator:

def __iter__(self):
    current = self.start
    while (self.step > 0 and current < self.end) or (self.step < 0 and current > self.end):
        yield current
        current += self.step

Generators

A function containing yield returns a generator — an iterator whose state is the paused function itself. The first script’s my_generator yields 1, 2, 3; generators are the easy way to write iterators and to stream data that does not fit in memory.

Two small notes from running the scripts. The last loop of b_iterable_and_loops1.py opens example.txt, which is not in the repository, so the script ends with a FileNotFoundError — create the file first. And in the second script, filter(lambda x: x % 2 == 0, doubled_numbers) keeps every element: doubling made them all even, so the filter has nothing to remove.

Try it yourself. Replace MyRange.__iter__ with the generator version above and confirm list(r) works twice. Then write def fib(): as an infinite generator and take the first ten values with itertools.islice.

View source on GitHub →