Code

Build Your Own Iterator

Any object can join the iteration protocol by defining two dunder methods:

  • __iter__(self) returns the iterator. For an iterator, that's just self.
  • __next__(self) returns the next value, or raises StopIteration when done.
class Doubling:
    def __init__(self, limit):
        self.value = 1
        self.limit = limit

    def __iter__(self):
        return self

    def __next__(self):
        if self.value > self.limit:
            raise StopIteration
        current = self.value
        self.value *= 2
        return current

print(list(Doubling(20)))  # [1, 2, 4, 8, 16]

That's it! Now for, list(), sum(), zip() and friends all work with it.

One rule to remember: once __next__ raises StopIteration, it should keep raising it on every later call. Iterators don't restart.

Assignment

Write a class Countdown:

  1. Countdown(start) stores where to start.
  2. Iterating over it gives start, start - 1, ..., 1, then stops. list(Countdown(3)) is [3, 2, 1].
  3. Countdown(0) (or any number below 1) gives nothing at all.
  4. __iter__ returns self.
  5. When it is finished, every later next() raises StopIteration again.