Skip to main content

next()

The next() function is a built-in Python function that retrieves the next item from an iterator by calling its __next__() method. If the iterator is exhausted, it raises a StopIteration exception.

Parameter Values

Parameter Description
iterator

An iterator object which represents a sequence of elements.

default

A value to return if the iterator is exhausted (reaches the end)

Return Values

The next() function in Python can return any data type present in the iterator it acts upon.

How to Use next() in Python

Example 1:

The next() function retrieves the next item from an iterator by calling its __next__() method.

next(iter([1, 2, 3]))
Example 2:

If the iterator is exhausted and no more items are available, default can be provided as a second argument to return when the iterator is exhausted.

it = iter([4, 5, 6])
print(next(it, 'No more items'))
Example 3:

Calling next() on an iterator that has reached the end without providing a default value will raise a StopIteration exception.

it = iter([7, 8, 9])
for _ in range(4):
    print(next(it))