Custom iterators
Create a custom object consumed by for loops.
Python · Module
__next__() is the iterator protocol method that returns the next item. It must raise StopIteration when the iterator is exhausted.
Define __next__ without arguments to produce the next value from an iterator. Once no values remain, it must raise StopIteration; iteration constructs use that exception to detect completion.
object.__next__()The next element of the iterator; raises StopIteration when no elements remain.
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current == 0:
raise StopIteration
self.current -= 1
return self.current + 1
for value in Countdown(3):
print(value)This iterator returns successive values and signals completion by raising StopIteration.
Create a custom object consumed by for loops.
Generate values incrementally without materializing a collection.
Control stateful traversal through a sequence or resource.
__iter__next()StopIterationiter()