Sub topic 14
Under the hood: iter(), next(), and StopIteration
This chapter explains the machinery behind every for loop. It assumes you can write for loops over lists, strings and range(), and that you know how to use try/except and define a simple class. By the end you should be able to read a for loop as a sequence of iter() and next() calls, and to explain several behaviors that otherwise look odd, such as an exhausted loop source or a skipped list item.
What a for loop really does
A for loop does not know about lists, strings or ranges. It only knows two operations: ask an object for an iterator, then ask that iterator for the next item until it says there are none left.
The loop below does the same work as for item in iterable: body(item):
def manual_for(iterable, body):
iterator = iter(iterable) # step 1: called once
while True:
try:
item = next(iterator) # step 2: called repeatedly
except StopIteration: # step 3: the signal that the data ran out
break
body(item)
manual_for(["a", "b", "c"], print)This prints a, b and c on separate lines. The for statement performs the same steps in the interpreter, which is faster than the Python version above.
Iterable versus iterator
Two terms are easy to mix up:
| Term | Required method | What it does | Example |
|---|---|---|---|
| Iterable | `__iter__()` | Returns a new iterator each time it is called | list, str, dict, tuple, set, range |
| Iterator | `__next__()` and `__iter__()` | Returns the next item, or raises `StopIteration` | the result of `iter([1, 2])`, file objects, generators |
iter(obj) calls obj.__iter__(). next(it) calls it.__next__(). An iterator's __iter__() returns the iterator itself, so passing an iterator to iter() gives you the same object back. That is why you can write for x in some_iterator and it works.
Driving an iterator by hand
You can call iter() and next() yourself:
it = iter([10, 20])
print(next(it)) # 10
print(next(it)) # 20
try:
next(it)
except StopIteration:
print("done")StopIteration is an exception, but in this design it is a normal signal and not a failure. A for loop catches it for you and ends quietly.
If you do not want an exception, give next() a second argument. It is returned instead of raising:
it = iter("ab")
print(next(it, "empty")) # a
print(next(it, "empty")) # b
print(next(it, "empty")) # emptyThis is a common way to take the first item of any iterable, such as first = next(iter(items), None).
Iterators are single use
An iterable can be looped over many times because each iter() call creates a fresh iterator. An iterator only moves forward. Once it is used up, it stays used up:
numbers = [1, 2, 3]
it = iter(numbers)
print(list(it)) # [1, 2, 3]
print(list(it)) # [] because the iterator is exhausted
print(list(numbers)) # [1, 2, 3]
print(list(numbers)) # [1, 2, 3] because the list makes a new iterator each time
print(iter(it) is it) # TrueExhaustion causes a common bug. If a function returns an iterator, such as map(...), zip(...), enumerate(...), a generator or an open file, then looping over it twice gives nothing the second time. Convert it with list() if you need to reuse the items.
range is different. It is an iterable, not an iterator. for i in r creates a new range_iterator every time, so a range object can be looped over repeatedly. You can check this: next(range(3)) raises TypeError, because a range has no __next__(), while next(iter(range(3))) returns 0.
Building your own iterator
Any class that provides __iter__() and __next__() works in a for loop:
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
for n in Countdown(3):
print(n) # 3, then 2, then 1This class is its own iterator, so it can only be used once. To make an object that can be looped over many times, keep the state in the iterator and not in the object. The simplest way is to make __iter__() a generator function:
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
c = Countdown(3)
print(list(c)) # [3, 2, 1]
print(list(c)) # [3, 2, 1] again, because each call to iter(c) starts a new generatorA function containing yield returns a generator, which is an iterator. When the function ends, Python raises StopIteration for you.
Older objects: the __getitem__ fallback
If an object has no __iter__() but has __getitem__(), iter() builds an iterator that calls obj[0], obj[1], obj[2] and so on. It stops when IndexError is raised. This is why some very old sequence classes still work in for loops. New code should define __iter__() instead.
What this explains about earlier behavior
Why removing items skips some
A list iterator stores a position, which is an index into the list. It does not store a copy. When you remove an item, the items after it shift left, but the iterator's index still increases by one:
nums = [2, 4, 6, 8]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # [4, 8], not []Here is the trace. At index 0 the loop sees 2 and removes it, leaving [4, 6, 8]. At index 1 it sees 6, skipping 4, and removes it, leaving [4, 8]. At index 2 the list has length 2, so the iterator raises StopIteration. The value 8 was never visited. Build a new list with a comprehension instead: nums = [n for n in nums if n % 2 != 0].
Dictionaries are stricter. Their iterator checks whether the size changed and raises an error:
d = {"a": 1}
try:
for key in d:
d["b"] = 2
except RuntimeError as error:
print(error) # dictionary changed size during iterationWhy the loop variable survives
The loop assigns each result of next() to the loop variable. After the final successful next(), nothing resets that name, so it keeps the last item. If the first next() raises StopIteration, nothing was ever assigned, which is why a loop over an empty iterable leaves the variable undefined.
Why the else clause works
The else clause of a loop runs when the loop ends because StopIteration was raised. A break leaves the loop without that signal, so else is skipped.
Common mistakes
- Looping twice over an iterator such as a
zipobject and getting nothing the second time. - Calling
next()on an iterable, such asnext([1, 2]), which raisesTypeError: 'list' object is not an iterator. Calliter()first. - Wrapping a
forloop intry/except StopIteration. The loop already handles it. Only catch it around your ownnext()calls. - Forgetting that
next(it)on an empty or finished iterator raises, unless you pass a default.
Exercise
What is the output of this code, and why? it = iter([1, 2, 3]) next(it) for x in it: print(x) print(next(it, "none"))
Show answer
It prints 2, then 3, then none. The first next(it) consumes 1 by hand. The for loop calls iter(it), which returns the same iterator, so it continues from 2 and ends when StopIteration is raised after 3. The iterator is now exhausted, so next(it, "none") returns the default "none".
Exercise
Write a class Repeat whose instances can be looped over several times. Repeat("x", 3) should yield "x" three times each time you loop over it. Then explain why a version with _iter_ returning self would fail on the second loop.
Show answer
class Repeat: def _init(self, value, times): self.value = value self.times = times def iter(self): for in range(self.times): yield self.value r = Repeat("x", 3) print(list(r)) # ['x', 'x', 'x'] print(list(r)) # ['x', 'x', 'x'] Each call to iter(r) runs _iter and creates a new generator with its own counter. If iter_ returned self, the object would be its own iterator and its counter would be used up after the first loop, so the second loop would produce nothing.