next()
Fetches the next item from an iterator. Once it is exhausted, returns a default value or raises StopIteration.
- Returns
- The next item of the iterator, or
default.
Example
#students = [
{"name": "Jack", "points": 80},
{"name": "Emma", "points": 250},
{"name": "Mia", "points": 310},
]
leader = next((s["name"] for s in students if s["points"] > 200), None)
print(leader)
nobody = next((s["name"] for s in students if s["points"] > 1000), None)
print(nobody)Definition and usage
#The next(iterator) function returns the next item of an iterator and moves it forward. It works on iterators and generators, but not directly on a list or a string: you first need to get an iterator from them with iter().
When items run out, next() raises StopIteration. If you give a second argument, it is returned instead of the exception, so next(iterator, None) safely fetches an item that might not be there.
Combining next() with a generator expression or filter() is very handy: next((s for s in students if s["points"] > 200), None) returns the first item matching the condition and stops searching as soon as it is found. Before a for loop, it is also convenient to skip the first row of data, like a header, with next().
Syntax
#next(iterator)
next(iterator, default)Parameters
#iterator
an iterator or generator
The object you fetch an item from. Convert a list first withiter().default
optional
The value returned when the iterator is exhausted. Without it, aStopIterationis raised.
More examples
#levels = iter([1, 2])
print(next(levels))
print(next(levels))
print(next(levels, "done"))
try:
next(levels)
except StopIteration:
print("StopIteration")lines = ["name;points", "Emma;250", "Jack;80"]
rows = iter(lines)
header = next(rows).split(";")
for line in rows:
print(dict(zip(header, line.split(";"))))def ticket_numbers(prefix):
number = 1
while True:
yield f"{prefix}-{number:03}"
number += 1
tickets = ticket_numbers("PY")
print(next(tickets))
print(next(tickets))
print(next(tickets))Good practices
#- When searching for the first matching item, use
next(generator, None)instead of building the whole list and taking[0]. The search stops at the first match, and no result raises noIndexError. - When you add a second argument next to a generator expression, wrap the expression in parentheses:
next((x for x in items), None). - Calling
next()on a list raises aTypeError, because a list is not an iterator. Useiter()first.
Related entries
#- iter()Returns an iterator for a collection, an object that hands out its items one at a time. This is the mechanism behind the for loop.
- yieldCreates a generator: a function that returns successive values on demand.
- forA loop that goes through the successive items of a sequence or other iterable object.
- filter()Returns an iterator of items for which a function returns a truthy value.
Spotted a mistake or missing an example? Write to us.