Python next() built-in function
From the Python 3 documentation
Retrieve the next item from the iterator by calling its __next__() method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
Introduction
The next()
function retrieves the next item from an iterator. If the iterator is exhausted, it raises a StopIteration
exception.
You can also provide a default value to be returned if the iterator is exhausted, which prevents the StopIteration
exception.
Examples
Using next()
with an iterator:
my_list = [1, 2]
my_iter = iter(my_list)
print(next(my_iter)) # Output: 1
print(next(my_iter)) # Output: 2
try:
print(next(my_iter))
except StopIteration:
print("Iterator is exhausted")
# Output: Iterator is exhausted
Using next()
with a default value:
my_iter = iter([1])
print(next(my_iter, "default")) # Output: 1
print(next(my_iter, "default")) # Output: default
More examples:
>>> i = iter([1, 2, 3])
>>> next(i)
# 1
>>> next(i)
# 2
>>> next(i)
# 3