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
| Parameter | Description |
|---|---|
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
it = iter(["a", "b"])
print(next(it), next(it), next(it, "end"))
Output
a b end
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
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
iter()· Get an iterator from an iterable, or create one that calls a function until it returns a sentinel value.anext()· Await and return the next item from an asynchronous iterator, or a default value when it is exhausted.filter()· Keep only the items of an iterable for which a function returns True. Returns a lazy iterator, not a list.- Python Iterators and Generators · tutorial