CKTIS / Python
iterator.__next__
The iterator method returns the next item and raises StopIteration when exhausted.
Version: Python 3.14; repository image, production runtime not attested
Syntax
item = next(iterator)The iterator method returns the next item and raises StopIteration when exhausted.
iterator.__next__
next(it) invokes the protocol, while next(it, default) substitutes the default on exhaustion. None can be an ordinary item. A conforming iterator remains exhausted on subsequent calls.
The first call yields 1, list consumes the remaining [0], and the final call yields end.
it=iter([None])
assert next(it) is None
for _ in range(2):
try: next(it)
except StopIteration: pass
else: raise AssertionError
Examples
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
it = Countdown(2)
print(next(it), list(it), next(it, "end"))
Result
1 [0] end
The first call yields 1, list consumes the remaining [0], and the final call yields end.