← Back to Python, page 3

python-0041 · Medium mid

Implement the iterator protocol for a class, and explain iterables versus iterators.

An iterable has __iter__ returning an iterator; an iterator has __next__, which returns the next value or raises StopIteration, and its own __iter__ returning itself. Containers should be iterables that return a fresh iterator each time, so they can be looped over repeatedly.

Full answer
python
class Countdown:
    def __init__(self, start): self.start = start
    def __iter__(self): return CountdownIterator(self.start)

class CountdownIterator:
    def __init__(self, n): self.n = n
    def __iter__(self): return self
    def __next__(self):
        if self.n <= 0:
            raise StopIteration
        self.n -= 1
        return self.n + 1

c = Countdown(3)
print(list(c), list(c))
it = iter(c)
print(next(it), next(it), next(it), next(it, "done"))
it2 = iter(c)
print(list(it2), list(it2))

Output:

text
[3, 2, 1] [3, 2, 1]
3 2 1 done
[3, 2, 1] []

Looping over Countdown twice works because each iter() call creates a new iterator. The iterator itself is single use: after it is exhausted, a second list() returns an empty list. next(it, default) returns the default instead of raising StopIteration. In practice, writing __iter__ as a generator function (def __iter__(self): yield from range(self.start, 0, -1)) gives the same behaviour with less code. for loops, list(), sum() and unpacking all use this protocol.

python
class Countdown:
    def __init__(self, start): self.start = start
    def __iter__(self): return CountdownIterator(self.start)

class CountdownIterator:
    def __init__(self, n): self.n = n
    def __iter__(self): return self
    def __next__(self):
        if self.n <= 0:
            raise StopIteration
        self.n -= 1
        return self.n + 1

c = Countdown(3)
print(list(c), list(c))
it = iter(c)
print(next(it), next(it), next(it), next(it, "done"))
it2 = iter(c)
print(list(it2), list(it2))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Iterables return iterators from __iter__
  • Iterators implement __next__ and raise StopIteration
  • Containers should return fresh iterators
  • Iterators are single use
  • Generators simplify __iter__

Common mistakes

  • Returning self from a container's __iter__
  • Forgetting StopIteration

Follow-ups

  • How does a for loop use these methods?
  • What does iter(callable, sentinel) do?

Tips

  • Separate iterable from iterator