The next()
function is used to retrieve the next item from an iterator object. If the iterator is empty, the function raises a StopIteration
exception.
In Python, an iterator is an object that implements the iterator protocol, which consists of the __iter__()
and __next__()
methods. The next()
function takes an iterator as an argument.
Syntax:
next(iterator, default)
The iterator
parameter is the iterator object from which you want to retrieve the next item. The optional default
parameter is used to provide a default value that will be returned if the iterator is exhausted (i.e., there are no more items to retrieve). If no default value is provided and the iterator is exhausted, the function will raise the StopIteration
exception.
We can use the built-in function iter to create an iterator.
L = [1, 2, 3]
iterator = iter(L)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
L = [1, 2, 3, 4, 5]
iterator = iter(L)
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator, 'END'))
T = ('Python', 'C++', 'Java', 'PHP')
iterator = iter(T)
try:
while True:
print(next(iterator))
except StopIteration:
print('END')