Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readPython
#iterators#generators#built-in functions#StopIteration
Illustration of Python next() function retrieving the next item from an iterator chain.

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:

python
numbers = [1, 2, 3] it = iter(numbers) print(next(it)) # 1 print(next(it)) # 2 print(next(it)) # 3

Each 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:

python
it = iter([1, 2]) print(next(it, None)) # 1 print(next(it, None)) # 2 print(next(it, None)) # None

If 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:

python
def countdown(n): while n > 0: yield n n -= 1 gen = countdown(3) print(next(gen)) # 3 print(next(gen)) # 2 print(next(gen)) # 1

The 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:

python
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:

python
it = iter(range(10)) next(it, None) # skip 0 next(it, None) # skip 1 print(next(it)) # 2

This 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:

python
from itertools import tee it1, it2 = tee(original_iterator) first = next(it1) # it2 still has all items, including the first

This 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 tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.