Python · Level 3 Iteration

Iterators

See what a for loop really does: make your own objects iterable with __iter__ and __next__.

  • iter() and next()
  • __iter__ returns the iterator
  • __next__ returns the next value or raises StopIteration

A for loop calls iter() on an object, then next() again and again until StopIteration is raised. Implement those two methods and your class works everywhere a list does.

it = iter(["a", "b"])
next(it)   # 'a'
next(it)   # 'b'
next(it)   # raises StopIteration, which ends a for loop

class Repeat:
    def __init__(self, word): self.word, self.left = word, 2
    def __iter__(self): return self
    def __next__(self):
        if not self.left: raise StopIteration
        self.left -= 1
        return self.word

Write a class Countdown(start) that can be iterated to produce start, start - 1, … down to 1.

solution.py
Test Suites Pending
Stdout