Python 3.0+Iterators & generatorsfunction
__next__
iterator protocol
The iterator method next() calls: it returns the next item or raises StopIteration.
Syntax
def __next__(self): ...
StopIteration signals the end rather than an error: the for loop catches it itself. Once an iterator has raised StopIteration it must keep raising it. Python 2 called the method next; in Python 3 it is __next__, and next(it) became a built-in with an optional default.
Examples
class Counter:
def __init__(self, limit):
self.i, self.limit = 0, limit
def __iter__(self):
return self
def __next__(self):
if self.i >= self.limit:
raise StopIteration
self.i += 1
return self.i
it = Counter(2)
print(next(it), next(it)) # → 1 2
print(next(it, 'конец')) # → конец — default вместо StopIteration
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy