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.
it = iter(["a", "b"]) next(it) # "a" next(it) # "b" next(it, None) # None (exhausted, default returned)
Try it
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.
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
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
forloop 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) ifNonecould be a legitimate value. StopIterationinside a generator is converted toRuntimeErrorsince Python 3.7. Do not let it escape from generator code; catch it or pass a default.- Calling
next(x)is the same asx.__next__(), but also works with thedefaultargument and gives clearer errors. - Infinite iterators such as
itertools.count()never raiseStopIteration;next()simply keeps producing values. - Strings, lists and dicts are not iterators. Wrap them with
iter()first.
Related
iter(),enumerate(),zip(),map()__iter__()and__next__()- Lessons: Iterators, Generators