Sub topic 14
Under the hood: iter(), next(), and StopIteration
This chapter assumes you can write basic for loops, know lists, strings and range(), and can run a Python 3 script. It shows what Python does each time a for loop runs.
Iterables and iterators
Two terms matter here.
- An iterable is an object you can loop over, such as a list, string, dictionary or
range. Callingiter()on it returns an iterator. - An iterator is an object that hands out one item per call to
next(). It remembers where it is.
A list is an iterable but not an iterator. You cannot call next() on a list directly.
What a for loop does
A statement such as for x in items: works in three steps.
- Python calls
iter(items)once and keeps the iterator it gets back. - Python calls
next()on that iterator before each pass and assigns the result tox. - When
next()raisesStopIteration, the loop ends quietly. The exception never reaches your code.
Doing it by hand
You can repeat the loop's steps yourself.
it = iter([10, 20])
print(next(it)) # 10
print(next(it)) # 20
try:
next(it)
except StopIteration:
print("done")The third call to next() finds no items left, so it raises StopIteration. A for loop catches that signal for you.
Here is a for loop rewritten as a while loop that does the same work.
items = ["a", "b", "c"]
it = iter(items)
while True:
try:
item = next(it)
except StopIteration:
break
print(item)Iterators are used up
An iterator moves forward only. Once it is exhausted, it stays exhausted.
it = iter([1, 2, 3])
print(list(it)) # [1, 2, 3]
print(list(it)) # []The second list(it) gives an empty list because the first call consumed every item. A list, by contrast, returns a fresh iterator each time you loop over it, so you can loop over it as often as you like.
nums = [1, 2, 3]
print(iter(nums) is iter(nums)) # False: each call makes a new iterator
it = iter(nums)
print(iter(it) is it) # True: an iterator returns itselfThat last line explains why you can put an iterator directly in a for loop: calling iter() on an iterator gives back the same object.
Common errors
- Calling
next()on an iterable that is not an iterator.next([1, 2])raisesTypeError: 'list' object is not an iterator. Wrap it withiter()first. - Looping over an iterator twice. The second loop does nothing, because the iterator is already used up.
- Letting
StopIterationescape. A barenext(it)on an empty iterator raises an error. Pass a default to avoid it:next(it, None)returnsNoneinstead of raising.
Exercise
What does this code print, and why? it = iter("ab") for ch in it: print(ch) print(next(it, "empty"))
Show answer
It prints a, then b, then empty. The for loop calls iter() on the iterator, which returns the same object, and consumes both characters. The final next() finds the iterator exhausted, so it returns the default value "empty" instead of raising StopIteration.