Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Python · Function

next

Retrieves one item from an iterator. An optional default value replaces StopIteration when the iterator is exhausted.

How it works

next() asks an iterator for its next item by invoking the iterator's __next__() method. If the iterator is exhausted, it raises StopIteration unless a default value is supplied; with a default, that value is returned instead.

Syntax

next(iterator, default, /)

Parameters

NameTypeDescription
iteratoriteratorThe iterator from which to retrieve the next item.
defaultobjectOptional value returned when the iterator is exhausted.

Returns

The iterator's next item, or default when supplied and the iterator is exhausted; otherwise it raises StopIteration.

Key points

  • The function advances an iterator by invoking its __next__() method.
  • An optional default is returned instead of raising when no item remains.
  • Without a default, exhaustion signals completion with StopIteration.
  • Each successful call obtains one item rather than consuming all remaining items.

Common mistakes

  • Without a default argument, calling next() on an exhausted iterator raises StopIteration; supplying a default prevents that exception.

Example: Read iterator items safely

values = iter([10, 20])
print(next(values))
print(next(values, "done"))
print(next(values, "done"))

Creates an iterator, retrieves its first two values, then uses a fallback after exhaustion.

When to use it

Incremental consumption

Consume one item at a time from a generator or iterator in imperative code.

Safe exhaustion handling

Provide a fallback when a possibly empty iterator has no next item.

First-result access

Peek at or retrieve the first matching result from an iterator.

Interview questions

QWhat does next() do?

next() retrieves one item from an iterator by calling its __next__() method. It returns the item produced by that method.

Follow-up: What happens at exhaustion? The call raises StopIteration unless a default argument was supplied.

QHow does the default argument work?

The optional default is returned when the iterator has no more items. This lets code handle exhaustion without catching StopIteration.

Follow-up: Does the default affect a non-exhausted iterator? No; the iterator's next item is returned instead.

QWhat kind of object does next() consume?

next() operates on iterators, not merely any iterable. An iterable must first provide an iterator, commonly with iter(), before next() can consume it.

Follow-up: How can a loop avoid calling next() directly? A for loop obtains and advances an iterator implicitly.

  • iter()
  • StopIteration
  • __next__()
  • for statement

Source: Built-in Functions. Checked 2026-10-16.