Python next(): Getting the Next Item from an Iterator
Learn how to use Python's next() to fetch the next item from iterators and generators, handle StopIteration, and work with streaming data.

Python's built-in next() function is the direct way to retrieve the next item from any iterator. When you call next(iterator), Python invokes the iterator's __next__() method and returns the value. This is the same mechanism that a for loop uses internally, but next() gives you explicit control over when and how you advance through a sequence.
How next() Works with Iterators
An iterator is any object that implements the iterator protocol: it has an __iter__() method returning itself and a __next__() method that returns the next value or raises StopIteration when exhausted. The next() built-in is a thin wrapper around __next__(). Consider a list iterator:
numbers = [1, 2, 3]
it = iter(numbers)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3Each call to next(it) advances the iterator by one position. The iter() function is required because lists themselves are not iterators; they are iterable. Once you have an iterator, next() is the standard way to manually pull values from it; you can also call it.__next__() directly, but the built-in adds the optional default-value behavior.
Handling StopIteration with a Default Value
When an iterator is exhausted, calling next() raises StopIteration. This exception is how Python signals that no more items are available. You can catch it explicitly, but next() also accepts a second argument that acts as a default value:
it = iter([1, 2])
print(next(it, None)) # 1
print(next(it, None)) # 2
print(next(it, None)) # NoneIf the iterator is empty from the start, the default is returned immediately. This pattern is useful when you want to retrieve the first element of a sequence without wrapping the call in a try/except block. It also lets you treat an empty iterator as a valid condition rather than an error.
Using next() with Generators
Generators are iterators created by functions that contain yield. Each call to next() on a generator resumes execution until the next yield statement. For example:
def countdown(n):
while n > 0:
yield n
n -= 1
gen = countdown(3)
print(next(gen)) # 3
print(next(gen)) # 2
print(next(gen)) # 1The generator state is preserved between calls. When the function completes without yielding, StopIteration is raised. This makes next() the primary tool for driving generator-based pipelines, especially when you need to coordinate multiple generators or pause execution at specific points.
Practical Patterns for Streaming Data
next() shines in scenarios where you process data incrementally. For instance, reading a file line by line without loading the entire file into memory:
with open('data.txt') as f:
first_line = next(f, None)
if first_line is not None:
print('Header:', first_line.strip())Here, next() fetches the first line and leaves the file iterator positioned at the second line. You can then loop over the remaining lines with a for loop. Another common pattern is skipping a fixed number of items:
it = iter(range(10))
next(it, None) # skip 0
next(it, None) # skip 1
print(next(it)) # 2This approach avoids slicing a list, which would copy the remaining items. It is especially effective with infinite iterators, such as itertools.count(), where you need to pull a specific number of values before starting your main processing loop.
Performance and Memory Implications
Because next() pulls one item at a time, it is inherently lazy. This means memory usage stays constant regardless of how many items you consume, as long as the underlying iterator does not buffer data. For example, a generator that reads from a network socket or a large file only holds one chunk in memory at a time. This is a significant advantage over materializing a list of all items.
The runtime cost of next() is minimal: it is a single function call that delegates to the iterator's __next__(). In tight loops, this overhead is negligible compared to the work of processing each item. However, if you need to advance many positions at once, consider itertools.islice() or a loop, as repeated next() calls add up. The key tradeoff is control versus convenience: next() gives you precise control but requires you to manage StopIteration manually when no default is provided.
Common Mistakes and Edge Cases
One frequent mistake is calling next() directly on an iterable that is not an iterator, such as a list or a string. These objects do not have a __next__() method, so next([1, 2]) raises TypeError. You must call iter() first.
Another edge case is using next() on an infinite iterator without a termination condition. If you call next() indefinitely, your program will never finish. Always ensure you have a break condition or a limit.
Also, be aware that next() consumes the item it returns. Once you call next(it), that item is gone from the iterator. If you need to look ahead without consuming, you must either store the value or use itertools.tee(). For example:
from itertools import tee
it1, it2 = tee(original_iterator)
first = next(it1)
# it2 still has all items, including the firstThis duplication comes at a memory cost, so use it only when necessary.
Finally, when working with custom iterator classes, ensure your __next__() method raises StopIteration exactly when the sequence is exhausted. If it raises a different exception, next() will propagate that exception, which can break code that expects the standard behavior.
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.