Python › Iterators & the Iterator Protocol
What does the built-in next() function's optional default argument do?
BeginnerAnswer
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 StopIterationReal-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.