The next(iterator[, default]) built-in function retrieves the next item from an iterator by invoking its underlying __next__() dunder method.
Manual Stream Traversal: If the iterator is exhausted and no fallback is provided, next() raises a StopIteration exception. Providing an optional default argument (next(it, fallback)) safely returns the fallback value instead of raising an error. It is the core idiom for extracting the first matching item from a stream and skipping header rows. To create iterators, see iter(), or reverse sequence ordering with reversed().
The next() function takes an active iterator and an optional default value:
# Formal syntax of built-in next()
item = next(iterator, default)
| Parameter | Type Accepted | Behavioral Details |
|---|---|---|
iterator |
Iterator object | An active iterator produced by iter(), a generator, or a class defining __next__(). |
default |
Any object (optional) | Returned when the iterator is exhausted. If omitted and exhausted, StopIteration is raised. |
| Return Value | Any element | Yields the next element produced by the iterator or the default fallback. |
To advance an iterable, first obtain an iterator using iter(), then step through with next():
# 1. Step-by-step iterator advancement
numbers = [18, 5, 15]
num_iter = iter(numbers)
print("First call: ", next(num_iter))
print("Second call:", next(num_iter))
print("Third call: ", next(num_iter))
# 2. Reaching the end raises StopIteration
try:
next(num_iter)
except StopIteration:
print("Iterator exhausted: StopIteration raised")
Output:
First call: 18
Second call: 5
Third call: 15
Iterator exhausted: StopIteration raised
Passing a second argument to next() prevents StopIteration crashes by cleanly supplying a fallback value when no more items remain:
# Suppressing StopIteration using a fallback default value
colors = iter(['red', 'green'])
print(next(colors, 'empty')) # red
print(next(colors, 'empty')) # green
print(next(colors, 'empty')) # empty (no exception raised!)
print(next(colors, 'empty')) # empty
Output:
red
green
empty
empty
Combining next() with a generator expression provides an efficient, short-circuiting method to find the first element satisfying a condition without looping over the rest of the collection:
# Idiomatic search: find the first matching item in a collection
users = [
{"id": 1, "name": "Alice", "role": "editor"},
{"id": 2, "name": "Bob", "role": "admin"},
{"id": 3, "name": "Charlie", "role": "admin"},
]
# Extracts the first matching element and immediately halts iteration
first_admin = next((u for u in users if u["role"] == "admin"), None)
print("First admin user found:", first_admin["name"])
# Safely handles cases where no match exists
missing = next((u for u in users if u["role"] == "guest"), {"name": "Anonymous"})
print("Role search fallback: ", missing["name"])
Output:
First admin user found: Bob
Role search fallback: Anonymous
When parsing CSV streams or log files, a single call to next() consumes and isolates the column header row, leaving the remaining iterator positioned at the first record:
import io
# Simulating a CSV data stream
csv_stream = io.StringIO(
"id,product,price\n"
"101,Desk Lamp,35.00\n"
"102,Mousepad,12.50\n"
"103,Webcam,28.00\n"
)
# Step 1: Strip and parse the header row with next()
header = next(csv_stream).strip().split(',')
print("Header fields:", header)
# Step 2: Stream remaining rows cleanly
for row in csv_stream:
print("Data row: ", row.strip().split(','))
Output:
Header fields: ['id', 'product', 'price']
Data row: ['101', 'Desk Lamp', '35.00']
Data row: ['102', 'Mousepad', '12.50']
Data row: ['103', 'Webcam', '28.00']
Custom classes can participate in the iterator protocol by implementing __iter__() and __next__():
# Custom countdown class implementing __next__
class Countdown:
def __init__(self, start: int):
self.count = start
def __iter__(self):
return self
def __next__(self):
if self.count <= 0:
raise StopIteration
val = self.count
self.count -= 1
return val
timer = Countdown(3)
print(next(timer))
print(next(timer))
print(next(timer))
print(next(timer, "Liftoff!"))
Output:
3
2
1
Liftoff!
list, dict, and str are iterables, not iterators. Calling next([1, 2]) directly raises TypeError: 'list' object is not an iterator.next(generator_expression) without a default value will throw an unhandled StopIteration if no elements match. Always provide a fallback like None.next() can lead to skipped items or RuntimeError.# Pitfall 1: Calling next() directly on an iterable (not an iterator)
raw_list = [10, 20]
try:
next(raw_list) # TypeError!
except TypeError as err:
print("TypeError caught:", err)
# Pitfall 2: Forgetting default value in search expressions
# If generator has 0 matching items and default is omitted, StopIteration is raised!
try:
val = next(x for x in [1, 3, 5] if x % 2 == 0)
except StopIteration:
print("Trap caught: Unhandled StopIteration on empty match")
Output:
TypeError caught: 'list' object is not an iterator
Trap caught: Unhandled StopIteration on empty match
Practice manual iterator stepping, default fallback handling, and first-match queries in our companion Jupyter Notebook:
Explore interactive code cells, implement first-match search pipelines, skip data stream headers, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify next() mechanics:
def test_next_mechanics():
# 1. Basic advancement
it = iter([1, 2])
assert next(it) == 1
assert next(it) == 2
# 2. Fallback default
assert next(it, "DONE") == "DONE"
# 3. First match search
items = [10, 25, 30, 45]
first_over_20 = next(x for x in items if x > 20)
assert first_over_20 == 25
# 4. Fallback search
no_match = next((x for x in items if x > 100), -1)
assert no_match == -1
print("All next() unit assertions passed! 100% verified.")
test_next_mechanics()
Output:
All next() unit assertions passed! 100% verified.
Produces iterator objects from collections or wraps callables with sentinels.
Creates stateful iterators easily using Python's yield keyword.
Generates reverse iterators across reversible sequences in constant memory.
Pairs an iterable's items with an automatically incremented integer counter.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.