next()
Returns the next item from an iterator or generator. With a default value it returns that instead of raising StopIteration at the end.
next(iterator)
next(iterator, default)next() asks an iterator for its next item. Each call moves one step forward. Iterators come from iter(), from generators, from files and from functions like zip() or map().
When the iterator has nothing left, next() raises StopIteration. Give it a second argument, a default, and it returns that value instead. That makes next() the neat way to find the first item that matches a condition: next((x for x in items if test(x)), None).
next() does not work on a list directly: a list is not an iterator. Call iter(my_list) first.
Parameters
| Parameter | What it is |
|---|---|
iteratorrequired | An iterator: the result of iter(), a generator, a file object, etc. |
defaultoptional | Returned when the iterator is used up. Without it, StopIteration is raised. |
Return value
The next item, or default when there are no items left.
Examples
1Step through an iterator
queue = iter(["Ana", "Ben", "Cleo"])
print("Now serving", next(queue))
print("Now serving", next(queue))
print("Next up:", next(queue))
print(next(queue, "Queue empty"))Now serving Ana Now serving Ben Next up: Cleo Queue empty
2Find the first match, or None
names = ["Lucas", "Maya", "Mateo", "Zoe"]
first_m = next((n for n in names if n.startswith("M")), None)
first_x = next((n for n in names if n.startswith("X")), None)
print(first_m)
print(first_x)Maya None
The round brackets around the generator are needed because there is a second argument.
3Skip a header row
Take the first item by hand with next(), then let the loop handle the rest.
rows = iter(["name,score", "Ivan,82", "Nora,95"])
header = next(rows)
print("Columns:", header.split(","))
for row in rows:
name, score = row.split(",")
print(name, int(score))Columns: ['name', 'score'] Ivan 82 Nora 95
4Drive a generator by hand
def countdown(n):
while n > 0:
yield n
n -= 1
timer = countdown(3)
print(next(timer))
print(next(timer))
print(next(timer))
print(next(timer, "Liftoff!"))3 2 1 Liftoff!
Common mistakes
Calling next() on a list
A list is iterable but it is not an iterator, so next(my_list) raises TypeError. Wrap it with iter().
scores = [10, 20]
try:
next(scores)
except TypeError:
print("TypeError: a list is not an iterator")
print(next(iter(scores)))TypeError: a list is not an iterator 10
Running past the end without a default
Without a default, next() raises StopIteration when the items run out. Either pass a default or catch the error.
it = iter([1])
next(it)
try:
next(it)
except StopIteration:
print("No more items")No more items
Questions people ask
How do I get the first item of a generator?
next(gen), or next(gen, None) if it might be empty.
How do I get the first item of a dict or set?
next(iter(my_dict)) gives the first key. Dicts keep insertion order; sets have no reliable order.
Can next() go back to an earlier item?
No. Iterators only move forward. Store items in a list if you need to look back.