Incremental consumption
Consume one item at a time from a generator or iterator in imperative code.
Python · Function
Retrieves one item from an iterator. An optional default value replaces StopIteration when the iterator is exhausted.
next() asks an iterator for its next item by invoking the iterator's __next__() method. If the iterator is exhausted, it raises StopIteration unless a default value is supplied; with a default, that value is returned instead.
next(iterator, default, /)| Name | Type | Description |
|---|---|---|
iterator | iterator | The iterator from which to retrieve the next item. |
default | object | Optional value returned when the iterator is exhausted. |
The iterator's next item, or default when supplied and the iterator is exhausted; otherwise it raises StopIteration.
values = iter([10, 20])
print(next(values))
print(next(values, "done"))
print(next(values, "done"))Creates an iterator, retrieves its first two values, then uses a fallback after exhaustion.
Consume one item at a time from a generator or iterator in imperative code.
Provide a fallback when a possibly empty iterator has no next item.
Peek at or retrieve the first matching result from an iterator.
next() retrieves one item from an iterator by calling its __next__() method. It returns the item produced by that method.
Follow-up: What happens at exhaustion? The call raises StopIteration unless a default argument was supplied.
The optional default is returned when the iterator has no more items. This lets code handle exhaustion without catching StopIteration.
Follow-up: Does the default affect a non-exhausted iterator? No; the iterator's next item is returned instead.
next() operates on iterators, not merely any iterable. An iterable must first provide an iterator, commonly with iter(), before next() can consume it.
Follow-up: How can a loop avoid calling next() directly? A for loop obtains and advances an iterator implicitly.
iter()StopIteration__next__()for statement