next() is one of Python's built-in functions used to retrieve the next element from an iterator.

Function Syntax

next(iterator[, default])

Parameters:

  • iterator: An iterator object.
  • default: Optional parameter, default value returned when the iterator is exhausted.

The next() function returns the next element from the iterator. If the iterator is exhausted, it raises a StopIteration exception. If default is specified, it returns default instead of raising an exception.

next() Function Examples

Here are several examples of the next() function:

# Get next element from a list
my_iter = iter([1, 2, 3, 4])
print(next(my_iter))        # 1
print(next(my_iter))        # 2
# next function actually calls __next__() method
print(my_iter.__next__())   # 3
print(my_iter.__next__())   # 4

# Specify default value
my_iter = iter([1, 2])
print(next(my_iter, 0))  # 1
print(next(my_iter, 0))  # 2
# Elements exhausted but no StopIteration raised
print(next(my_iter, 0))  # 0

The next() function actually calls the iterator's __next__() method:

class myclass:
    def __next__(self):
        return 1

a = myclass()
print(next(a))  # 1