How to Use Python's next() Builtin with a Default Sentinel Value
A wrapper function that returns the next item from an iterator, or a default sentinel value when the iterator is exhausted.
Python code
15 linesdef get_next_or_default(iterator, default=None):
"""Return the next item from an iterator, or default if exhausted."""
return next(iterator, default)
if __name__ == "__main__":
fruits = iter(["apple", "banana", "cherry"])
print(get_next_or_default(fruits)) # apple
print(get_next_or_default(fruits)) # banana
print(get_next_or_default(fruits)) # cherry
print(get_next_or_default(fruits, "none")) # none (iterator exhausted)
empty_list = iter([])
print(get_next_or_default(empty_list, "empty")) # empty
Output
apple
banana
cherry
none
empty
How it works
The next() builtin in Python accepts an optional second argument that is returned when the iterator is exhausted. By passing a default value like None or a custom sentinel, you avoid raising the StopIteration exception. This wrapper function encapsulates that pattern, making it reusable and explicit at the call site. The default parameter defaults to None, but callers can override it with any value, such as a string or a custom object.
Common mistakes
- Forgetting that `next()` without a default raises `StopIteration` when the iterator is empty
- Passing a mutable object like a list as the default, which gets shared across calls
- Confusing the iterator itself with the sequence — `iter()` must be called before passing to `next()`
Variations
- Use a sentinel object like `object()` to distinguish 'no more items' from a meaningful `None` value
- Loop directly with `for item in iterator` to avoid manual `next()` calls entirely
Real-world use cases
- Streaming paginated API responses where a default value handles the final empty page.
- Processing command-line arguments or config tokens in a loop that needs a fallback.
- Iterating over socket or file chunks when the stream ends unexpectedly.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.