Advertisement
Beginner Python, Iterators & the Iterator Protocol

How do you manually exhaust and inspect an iterator without a for-loop?

Short answer

Use iter() to get an iterator from an iterable, then call next() repeatedly, optionally wrapped in try/except StopIteration or with a default value, to pull and inspect values one at a time -- useful for peeking at the first item or interleaving manual logic with iteration.

Save Python mock interview
Advertisement
AModel answer
Use iter() to get an iterator from an iterable, then call next() repeatedly, optionally wrapped in try/except StopIteration or with a default value, to pull and inspect values one at a time -- useful for peeking at the first item or interleaving manual logic with iteration.
data = [10, 20, 30]
it = iter(data)
first = next(it)
print('First:', first)
print('Rest:', list(it))  # [20, 30]
Real-world example
A CSV parser peeks at the first row with next(it) to detect and validate the header before processing the remaining rows with a for-loop.
Likely follow-ups
  • How would you 'push back' a value onto an iterator?
  • What's itertools.chain used for combining a peeked value with the rest?
Related topics