Python 3 reference · Built-in Functions

Python next() Function

Get the next item from an iterator. When it is exhausted, return the default if given, otherwise raise StopIteration.

Python 3 Since 3.0

Syntax

next(iterator)
next(iterator, default)

Parameters

ParameterDescription
iterator An iterator (use iter() to get one from a list).
default optional Returned instead of raising StopIteration.

Return value

The next item, or default.

Examples

Step through an iteratorTry it yourself
it = iter(["a", "b"])
print(next(it), next(it), next(it, "end"))

Output

a b end
Find the first matchTry it yourself
numbers = [3, 8, 12, 5]
first_big = next((n for n in numbers if n > 7), None)
print(first_big)
print(next((n for n in numbers if n > 100), None))

Output

8
None

Good to know

next(generator, None) is the idiomatic way to find the first matching item without building a whole list.

Version history

VersionChange
Python 3.0Added