Python next() function is used to retrieve the next item from an iterator.
This function is particularly useful when you have an explicit iterator and you want to manually fetch its items one by one.
Syntax
next(iterator, default)
Parameters
- iterator(required): This is the iterator object from which you want to retrieve the next item.
- default (optional): It is returned by the next() function if the iterator is exhausted (i.e., there are no more items). If default is not provided and the iterator is exhausted, a StopIteration exception is raised.
Return value
It returns next item from iterator.
Example 1: Passing single parameter
# List of numbers
number_list = [111, 222, 333, 444, 555]
# Creating an iterator from the number list
number_iterator = iter(number_list)
print(next(number_iterator))
print(next(number_iterator))
print(next(number_iterator))
print(next(number_iterator))
print(next(number_iterator))
# Since the iterator is exhausted, this will raise a StopIteration exception
print(next(number_iterator))
Output
111
222
333
444
555
Traceback (most recent call last):
File "/Users/ankitlathiya/Desktop/code/app1.py", line 14, in <module>
print(next(number_iterator))
^^^^^^^^^^^^^^^^^^^^^
StopIteration
Example 2: Passing a default parameter
# List of numbers
number_list = [111, 222, 333, 444, 555]
# Creating an iterator from the number list
number_iterator = iter(number_list)
print(next(number_iterator, 'No More Items'))
print(next(number_iterator, 'No More Items'))
print(next(number_iterator, 'No More Items'))
print(next(number_iterator, 'No More Items'))
print(next(number_iterator, 'No More Items'))
print(next(number_iterator, 'No More Items'))
Output
111
222
333
444
555
No More Items