Sub topic 1
Iterables and iterators: what a for loop consumes
Prerequisites
This chapter assumes you can already:
- Write basic Python syntax and
forloops over lists. - Work with lists, tuples, and dictionaries.
- Call functions and use their return values.
Later chapters use enumerate and zip. Both depend on the model described here.
What a for loop needs
A for loop does not need a list. It needs something it can ask for one item at a time. Python names the two roles involved:
- An iterable is an object you can loop over. Lists, tuples, strings, dictionaries, sets, and files are iterables.
- An iterator is an object that hands out items one at a time and remembers where it is.
An iterable can produce a fresh iterator on request. You request one with the built-in iter(). You ask an iterator for its next item with the built-in next().
numbers = [10, 20, 30]
it = iter(numbers)
print(next(it)) # 10
print(next(it)) # 20
print(next(it)) # 30
try:
next(it)
except StopIteration:
print("no items left")When the iterator has no items left, next() raises StopIteration. This is the normal signal for "finished", not a bug.
What the for loop does
A for loop automates the steps above. It calls iter() once on the object you give it. It then calls next() repeatedly until StopIteration is raised. The loop catches that exception and exits quietly.
numbers = [10, 20, 30]
# This loop...
for item in numbers:
print(item)
# ...behaves like this one:
it = iter(numbers)
while True:
try:
item = next(it)
except StopIteration:
break
print(item)Iterable versus iterator
Every iterator is also an iterable. Calling iter() on an iterator returns the same object. A list is different: each iter() call on a list creates a new iterator.
numbers = [1, 2, 3]
it = iter(numbers)
print(iter(numbers) is numbers) # False: a new iterator each time
print(iter(it) is it) # True: an iterator returns itselfThis explains why you can loop over a list many times but not over an iterator. Each loop over the list starts with a fresh iterator. An iterator has only one position, and it never goes backward.
| Capability | List (iterable) | Iterator |
|---|---|---|
| Loop over it with `for` | Yes, any number of times | Yes, but only until it is used up |
| `next(obj)` | No, raises `TypeError` | Yes |
| `len(obj)` | Yes | Usually no |
| `obj[0]` | Yes | No |
| Restart from the beginning | Automatic with each new loop | Not possible; create a new one |
Iterators remember their position
Because an iterator keeps its place, a second loop over the same iterator continues where the first one stopped.
it = iter([1, 2, 3, 4])
for x in it:
if x == 2:
break
print(list(it)) # [3, 4]The loop consumed 1 and 2, then stopped. The remaining items, 3 and 4, are still waiting. Calling list(it) drains them. A second list(it) would return [].
Why this matters for enumerate and zip
The next chapters build on these two facts:
enumerate(...)andzip(...)accept any iterable as input. They are not limited to lists. Files, strings, and other iterators work too.- Both return iterators, not lists. Their results are produced lazily, one item per
next()call, and they can be consumed only once.
You can confirm the second fact now without knowing how either function works yet:
e = enumerate(["a", "b"])
z = zip([1, 2], ["x", "y"])
print(iter(e) is e) # True
print(iter(z) is z) # TrueBoth checks print True, so both objects are iterators. If you need to look at the results more than once, convert them with list() first. You can also create a new enumerate or zip each time you need one.
Common errors
These mistakes come directly from treating an iterator like a list:
- Indexing an iterator.
iter([1, 2, 3])[0]raisesTypeError: 'list_iterator' object is not subscriptable. Convert to a list first if you need indexing. - Calling
len()on an iterator. Most iterators do not know how many items remain, solen(iter([1, 2, 3]))raisesTypeError. - Calling
next()on a list.next([1, 2, 3])raisesTypeError: 'list' object is not an iterator. Wrap it withiter()first. - Looping twice over a used-up iterator. The second loop runs zero times and raises no error, so the bug is silent.
Exercise
A student writes it = iter(["a", "b", "c"]), then runs for x in it: print(x) twice in a row. What is printed, and why?
Show answer
The first loop prints a, b, and c on separate lines. The second loop prints nothing. The first loop consumed the iterator, and an iterator cannot restart. The second loop calls next(), immediately gets StopIteration, and exits without running its body. Looping over the list ["a", "b", "c"] twice would print the items both times, because each loop would get a fresh iterator.