Advance with iter and next
Core idea
next(it) retrieves one item and advances the iterator. Exhaustion raises StopIteration; next(it, default) returns the supplied fallback instead. iter(callable, sentinel) repeatedly invokes a zero-argument callable until its result equals the sentinel, which is not yielded.
Zero is a valid item, not an exhaustion signal.
Intentional exhaustion error
Without a default the empty iterator signals completion.
Stop at a marker
items = iter(["A", "B", "STOP", "C"])reader = iter(items.__next__, "STOP")print(list(reader))print(next(items))The callable returns each item; the equal marker ends the outer iterator.
Common mistake
A fallback may also be a real item. When that matters, use a unique object as a marker and compare by identity, or catch StopIteration. Other exceptions are not exhaustion.
Practice
Consume an iterator containing None using a unique object() marker; stop only when the marker is returned.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Iter and next
Check your understanding of iter and next.
What is printed?
it = iter([None])print(next(it, "end"), next(it, "end"))What happens?
next(iter(()))What is printed?
it = iter([1, 2, 0, 3])print(list(iter(it.__next__, 0)))When a real item can equal your fallback, which technique distinguishes exhaustion?