all Python 3Built-in functionsterm
next
iterators
Returns the next item of an iterator. default is returned if the iterator is exhausted.
Syntax
next(iterator[, default])
next takes an iterator, not a container: next([1, 2, 3]) is a TypeError — wrap the list in iter() first. Without the second argument an exhausted iterator raises StopIteration, so either catch it or pass a default. Inside a generator this matters even more: an unhandled StopIteration is converted into RuntimeError (PEP 479), which hides where the problem actually came from.
Examples
it = iter([1,2,3])
print(next(it)) # → 1
print(next(it)) # → 2
print(next(it)) # → 3
print(next(it, 'end')) # → end
g = (x**2 for x in range(5))
print(next(g), next(g)) # → 0 1
See also
Open in the full glossarydocs.python.orgReport an inaccuracy