In Python, next(iterator) asks an iterator for its next item. When there are no items left, it raises StopIteration, unless you pass a second argument: next(iterator, default) then returns the default instead.
It only works on iterators, not on plain lists; call iter() first. Combined with a generator expression, next(..., None) is the idiomatic way to get the first matching item or None.
next() is a built-in function: it lives in the builtins module, so it is always available without an import.
Required. An object with __next__(), such as the result of iter() or a generator.
default
Optional. Returned instead of raising StopIteration when the iterator is exhausted.
Return Value
Return Value
Description
any
The next item, or default if given and the iterator is empty.
Python Examples
Example 1 — Read Items Until the Iterator Is Empty
Pull two items, use a default for the third, then let next() raise.
python
it = iter([10, 20])
print(next(it))
print(next(it))
print(next(it, "done"))
try:
next(it)
except StopIteration:
print("StopIteration: the iterator is empty")
Output
10
20
done
StopIteration: the iterator is empty
How It Works
In order. The first two calls return 10 and 20.
Default instead of an error. The iterator is empty, so next(it, "done") returns "done".
No default, no mercy. The same call without a default raises StopIteration.
Still empty. Returning the default does not reset the iterator.
Example 2 — Find the First Matching Item
Combine a generator expression with a default to find the first admin, or None.
python
users = [
{"name": "ana", "admin": False},
{"name": "ben", "admin": True},
{"name": "cy", "admin": True},
]
first_admin = next((u["name"] for u in users if u["admin"]), None)
print(first_admin)
first_zoe = next((u["name"] for u in users if u["name"] == "zoe"), None)
print(first_zoe)
Output
ben
None
How It Works
Lazy search. The generator checks users one by one and stops at ben; cy is never examined.
Extra parentheses. With a second argument, the generator expression needs its own brackets.
No match. Nobody is named zoe, so the default None is returned instead of an exception.
Cheaper than a list. Building a full list just to take [0] would scan everything.
Example 3 — Step a Generator and Skip a Header Row
Advance a generator by hand, then consume the first line of CSV-like data separately.
python
def countdown(n):
while n > 0:
yield n
n -= 1
gen = countdown(3)
print(next(gen), next(gen))
print(list(gen))
rows = iter(["name,score", "ana,90", "ben,85"])
header = next(rows)
print(header.split(","))
for row in rows:
print(row.split(","))