Skip to content
UPEEC

Iterators and the Iterator Protocol

Any object with __iter__ and __next__ can be looped over; next() raises StopIteration at the end.

Intermediate
Comments 0
it = iter([10, 20])
next(it)   # 10
next(it)   # 20
next(it)   # StopIteration

class Countdown:
    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

for loops call iter() once and next() repeatedly. Generators are the easy way to write iterators.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.