Python next() Function

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.

Usage of Python next() Function

Syntax

next(iterator, default)

Parameters

  1. iterator(required): This is the iterator object from which you want to retrieve the next item.
  2. 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

Passing a Default Parameter to the next() Function.

# 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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.