Sub topic 2
The iterator protocol: __iter__, __next__ and StopIteration
This chapter assumes you know Python functions, classes and try/except, and that you know what a dunder (double-underscore) method is. It covers the two methods that define iteration in Python and the signal that ends it.
Two methods, two roles
The iterator protocol is a contract made of two special methods:
__iter__()returns an iterator. Built-initer(obj)calls it.__next__()returns the next value, or raisesStopIterationwhen no values remain. Built-innext(obj)calls it.
An iterable is any object with __iter__. An iterator is an object with both __iter__ and __next__. Lists, tuples, dicts and strings are iterables. They are not iterators, because they have no __next__.
numbers = [10, 20]
it = iter(numbers)
print(next(it)) # 10
print(next(it)) # 20
try:
next(it)
except StopIteration:
print("exhausted")iter(numbers) builds a separate iterator that remembers its position in the list. The list itself stays unchanged.
StopIteration is a signal
StopIteration is not a failure. It is the agreed way for an iterator to say "I am finished". Code that consumes iterators, such as list(), sum() and for loops, catches it for you. Only code that calls next() directly needs to handle it, or it can pass a default: next(it, None) returns None instead of raising.
A minimal iterator
Here is a class that follows the protocol:
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
print(list(Countdown(3))) # [3, 2, 1]__iter__ returns self because the object is already an iterator. This is the convention: calling iter() on an iterator must give back the same iterator. That rule lets you pass an iterator anywhere an iterable is expected. The next chapters look at how loops use this and at designing iterator classes.
Common errors
| Mistake | Result |
|---|---|
| Calling `next()` on a list | `TypeError: 'list' object is not an iterator`. Call `iter()` first. |
| Defining `__next__` but no `__iter__` | The object cannot be used in a `for` loop or passed to `list()`. |
| Returning `None` at the end of `__next__` | The iteration never stops, and `None` appears as a value. Raise `StopIteration`. |
| Reusing an iterator after it is exhausted | It yields nothing. Call `iter()` on the original iterable for a fresh one. |
Exercise
What does iter(it) is it evaluate to when it is an iterator made by it = iter([1, 2, 3]), and why is iter(lst) is lst false for a list lst?
Show answer
The first is True because an iterator's __iter__ returns itself. The second is False because a list's __iter__ creates a new iterator object each time, so the list and its iterator are different objects.