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.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 14 views 0 copies

Python code

15 lines
Python 3.9+
def 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

stdout
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

  1. Use a sentinel object like `object()` to distinguish 'no more items' from a meaningful `None` value
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.