Python next() Function: Usage and Error Handling
Learn how Python's next() function retrieves items from iterators, handles StopIteration, and uses default values in practical code.

The built-in next() function in Python returns the next item from an iterator. It is a fundamental part of the iteration protocol, and understanding its behavior is essential for working with generators, file objects, and custom iterators.
Signature and Basic Behavior
The next() function has a simple signature: next(iterator[, default]). It takes an iterator as its first argument and an optional default value as its second. When called, it returns the next item from the iterator. If the iterator is exhausted and no default is provided, it raises StopIteration. If a default is provided, that default is returned instead.
data = iter([1, 2, 3])
print(next(data)) # 1
print(next(data)) # 2
print(next(data)) # 3After the last item, calling next(data) again raises StopIteration. This is the same signal that for loops rely on internally: they repeatedly call __next__() on an iterator and stop when they receive StopIteration. The built-in next() function lets you drive that process manually.
Using next() with Iterators and Generators
next() works with any object that implements the iterator protocol, meaning it has a __next__() method. This includes generator objects, which are created by generator functions or generator expressions. Generators produce values lazily, and next() triggers the execution of the generator until the next yield statement.
def count_up_to(n):
i = 1
while i <= n:
yield i
i += 1
gen = count_up_to(3)
print(next(gen)) # 1
print(next(gen)) # 2
print(next(gen)) # 3When a generator is exhausted, it raises StopIteration. In practice, you rarely call next() directly on a generator because a for loop handles the iteration for you, but next() becomes valuable when you need to manually control the consumption of values.
Providing a Default Value to Avoid StopIteration
The optional second argument to next() is a default value that is returned when the iterator is exhausted. This is useful when you want to avoid handling StopIteration explicitly, especially when the absence of a value is a normal condition rather than an error.
data = iter([10, 20])
print(next(data, None)) # 10
print(next(data, None)) # 20
print(next(data, None)) # NoneUsing None as a default is common, but you can use any value that makes sense in your context. For example, you might return an empty string, a zero, or a sentinel object. This pattern can also be convenient when reading from a file until EOF or consuming items from a queue that may be empty.
Handling StopIteration Explicitly
In some situations, you need to know exactly when an iterator is exhausted, and the default value is not sufficient. You can catch StopIteration explicitly to perform specific actions when the iterator runs out of items.
data = iter([1, 2])
while True:
try:
item = next(data)
print(item)
except StopIteration:
print("No more items")
breakThis pattern is useful when you need to distinguish between a valid value and the end of iteration. For instance, if you are processing a stream and the absence of a value means you should close a resource or change control flow, catching StopIteration gives you that control. A StopIteration that is raised inside a generator and not handled there is converted to RuntimeError in Python 3.7 and later, so be careful when mixing these constructs.
Common Patterns: Peeking, Batching, and Consuming
next() enables several practical patterns that are awkward to implement with a for loop alone. One common pattern is peeking at the first item of an iterator to decide how to process the rest. In the example below, handle_first and handle_rest would be your own processing functions.
def process_first_then_rest(iterator):
try:
first = next(iterator)
except StopIteration:
return # nothing to process
handle_first(first)
for item in iterator:
handle_rest(item)Another pattern is batching items into groups of a fixed size; the code assumes size is positive. By repeatedly calling next() and catching StopIteration, you can build chunks without loading the entire iterator into memory.
def batched(iterator, size):
while True:
batch = []
try:
for _ in range(size):
batch.append(next(iterator))
except StopIteration:
if batch:
yield batch
break
yield batchThese patterns show how next() gives you fine-grained control over iteration, which is especially valuable when working with infinite generators or large data streams.
Performance and Memory Considerations
next() itself is a thin wrapper around the iterator's __next__() method, so its overhead is minimal. The performance characteristics of calling next() depend on the underlying iterator. For list iterators, it is a constant-time operation. For generators, each call resumes the generator frame, which involves some overhead but is still efficient for most use cases.
Memory usage is one of the main reasons to use next() directly: it allows you to process items one at a time without storing the entire sequence. This is particularly important when working with large files or infinite sequences. In Python 3, lazy iterators such as those returned by map() and filter() also produce items on demand, so using next() with them avoids building intermediate lists.
If you find yourself calling next() in a tight loop, consider whether a for loop or a comprehension would be more readable. The performance difference is usually negligible, but clarity matters. next() is best used when you need to manually control the iteration flow, not as a replacement for normal looping.
Edge Cases and Compatibility Notes
next() is available in all modern Python versions, but its behavior with custom iterators depends on the __next__() method. If you define a class that implements __iter__() and __next__(), you can pass an instance of that class to next() directly. However, if the object is only iterable but not an iterator (it has __iter__() but not __next__()), you must call iter() on it first.
class CountDown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
counter = CountDown(3)
print(next(counter)) # 3
print(next(counter)) # 2
print(next(counter)) # 1One subtle point is that next(iterator, default) treats any StopIteration raised by __next__() as the end of iteration. If a custom iterator uses StopIteration for internal control flow, you cannot rely on the default argument to distinguish that situation from normal exhaustion. In such a case, call next() without a default and catch StopIteration, or use a more specific exception for control flow.
Another compatibility note: in Python 2.6 and later, the built-in next() function is available, but the iterator method was named next() without underscores. In Python 3, that method is __next__(). If you are maintaining code across both versions, use the built-in next() function rather than calling the method directly.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.