Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python next() function

Reference for Python next(): fetch the next item from an iterator, supply a default to avoid StopIteration, and find the first match in a generator.

The built-in next() function asks an iterator for its next item. Each call moves the iterator forward by one step. When the iterator has nothing left, next() raises StopIteration, unless you passed a second argument, which is then returned instead.

next() needs an iterator, not just any iterable. A list is iterable but is not an iterator; call iter() on it first. Generators, file objects, zip(), map() and enumerate() objects are already iterators.

Python
it = iter(["a", "b"])
next(it)          # "a"
next(it)          # "b"
next(it, None)    # None (exhausted, default returned)

Try it

Python Stepping through an iterator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python First match and skipping a header

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
next(iterator)
next(iterator, default)
Name Description
iterator An object that implements __next__().
default Optional. Returned instead of raising StopIteration when the iterator is exhausted.

Return value: the next item, or default when exhausted.

Raises: StopIteration when exhausted and no default was given. TypeError if the argument is not an iterator.

Usage notes

  • It consumes the item. The iterator moves on, so the value will not appear again in a later for loop over the same iterator. That is exactly how the header-skipping example works.
  • next(gen_expr, default) is the idiomatic "first match". It stops at the first item that qualifies and never builds a full list.
  • Use a default that cannot be a real item (or a unique object() sentinel) if None could be a legitimate value.
  • StopIteration inside a generator is converted to RuntimeError since Python 3.7. Do not let it escape from generator code; catch it or pass a default.
  • Calling next(x) is the same as x.__next__(), but also works with the default argument and gives clearer errors.
  • Infinite iterators such as itertools.count() never raise StopIteration; next() simply keeps producing values.
  • Strings, lists and dicts are not iterators. Wrap them with iter() first.