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.
On this page

Example

#
Python
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)
Resultsaved result, you can check it
Emma
None

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

#
Syntax
next(iterator)
next(iterator, default)

Parameters

#
  • iterator

    an iterator or generator

    The object you fetch an item from. Convert a list first with iter().
  • default

    optional

    The value returned when the iterator is exhausted. Without it, a StopIteration is raised.

More examples

#
Fetching by hand and StopIteration
Python
levels = iter([1, 2])

print(next(levels))
print(next(levels))
print(next(levels, "done"))

try:
    next(levels)
except StopIteration:
    print("StopIteration")
Resultsaved result, you can check it
1
2
done
StopIteration
Skipping a header row
Python
lines = ["name;points", "Emma;250", "Jack;80"]
rows = iter(lines)

header = next(rows).split(";")
for line in rows:
    print(dict(zip(header, line.split(";"))))
Resultsaved result, you can check it
{'name': 'Emma', 'points': '250'}
{'name': 'Jack', 'points': '80'}
Successive values from a generator
Python
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))
Resultsaved result, you can check it
PY-001
PY-002
PY-003

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 no IndexError.
  • 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 a TypeError, because a list is not an iterator. Use iter() first.

Related entries

#

Spotted a mistake or missing an example? Write to us.