Advertisement
Beginner Python, Iterators & the Iterator Protocol

What does the built-in next() function's optional default argument do?

Short answer

next(iterator, default) returns default instead of raising StopIteration when the iterator is exhausted. This avoids needing a try/except block when you just want a fallback value for an empty or finished iterator.

Save Python mock interview
Advertisement
AModel answer
next(iterator, default) returns default instead of raising StopIteration when the iterator is exhausted. This avoids needing a try/except block when you just want a fallback value for an empty or finished iterator.
empty = iter([])
print(next(empty, 'no items'))  # 'no items' instead of StopIteration
Real-world example
A search function uses next((x for x in items if x.match), None) to get the first matching item or None without writing an explicit loop.
Likely follow-ups
  • How does this pattern replace a manual for-loop with early return?
  • Is there a performance cost to the default check?
Related topics