next()

The built-in next() function retrieves the next item from an iterator, raising a StopIteration exception when the iterator is exhausted:

Python
>>> numbers = iter([1, 2, 3])
>>> next(numbers)
1
>>> next(numbers)
2
>>> next(numbers)
3
>>> next(numbers) # Exhausted iterator
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

It can also return a default value if the iterator is exhausted, preventing a StopIteration exception:

Python
>>> numbers = iter([1, 2, 3])
>>> next(numbers, "End")
1
>>> next(numbers, "End")
2
>>> next(numbers, "End")
3
>>> next(numbers, "End")
'End' # Default value

next() Signature

Python Syntax
next(iterator)
next(iterator, default)

Arguments

Argument Description
iterator The iterator from which to retrieve the next item.
default The value to return if the iterator is exhausted, preventing the StopIteration exception.

Return Value

  • If the iterator has remaining items, next() returns the next item from the iterator.
  • If the iterator is exhausted and a default is provided, next() returns the default value.
  • If the iterator is exhausted and no default is provided, next() raises a StopIteration exception.

next() Examples

With an iterator as an argument:

Python
>>> fruits_it = iter(["apple", "banana", "cherry"])
>>> next(fruits_it)
'apple'
>>> next(fruits_it)
'banana'
>>> next(fruits_it)
'cherry'
>>> next(fruits_it)
Traceback (most recent call last):
    ...
StopIteration

With a default value:

Python
>>> numbers_it = iter([10, 20])
>>> next(numbers_it, "No more items")
10
>>> next(numbers_it, "No more items")
20
>>> next(numbers_it, "No more items")
'No more items'

next() Common Use Cases

The most common use cases for the next() function include:

  • Manually iterating over an iterator when you need to control the flow of iteration.
  • Skipping the first item of an iterator, such as a header line in a CSV file.
  • Providing a default value to avoid StopIteration exceptions when an iterator is exhausted.

next() Real-World Example

A typical use case for next() is reading a CSV file and skipping the header line:

Python
with open("data.csv") as file:
    next(file)  # Skip the header line
    for line in file:
        print(line.strip())

In this example, next(file) skips the first line of the file, which contains the headers, allowing the for loop to process only the data lines.

next() in Custom Classes

You can support next() in your custom classes by implementing the .__next__() method. Say that you want to write an iterator that takes a sequence of numbers, computes the square value of each number, and yields those values on demand. In this case, you can write the following class:

Python square_iter.py
class SquareIterator:
    def __init__(self, sequence):
        self._sequence = sequence
        self._index = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self._index < len(self._sequence):
            square = self._sequence[self._index] ** 2
            self._index += 1
            return square
        else:
            raise StopIteration

This class takes a sequence of numbers as an argument and makes an iterator of square values. The .__next__() method processes the current number and returns its square value. When the data is over, then .__next__() raises the StopIteration exception.

Tutorial

Iterators and Iterables in Python: Run Efficient Iterations

In this tutorial, you'll learn what iterators and iterables are in Python. You'll learn how they differ and when to use them in your code. You'll also learn how to create your own iterators and iterables to make data processing more efficient.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 7, 2024 • Reviewed by Dan Bader