Sub topic 1
Iterables and iterators: what is the difference?
Prerequisites
This chapter assumes you can write Python functions, classes, and loops. You should know the built-in collections (lists, tuples, dicts, strings), how try/except works, and what a special (dunder) method is.
Two words, two roles
Python separates two ideas that are easy to mix up.
- An iterable is an object you can loop over. It can hand out a fresh iterator on request. Lists, tuples, strings, dicts, sets, and files are iterables.
- An iterator is an object that produces values one at a time and remembers where it is. It is the thing that does the walking.
An iterable is like a book. An iterator is a bookmark moving through it. You can put many bookmarks in one book, and each keeps its own place.
Connecting them with iter() and next()
The built-in iter() takes an iterable and returns an iterator. The built-in next() asks an iterator for its next value. When no values remain, next() raises StopIteration.
numbers = [10, 20]
it = iter(numbers)
print(next(it)) # 10
print(next(it)) # 20
try:
next(it)
except StopIteration:
print("exhausted")The list numbers is the iterable. The object it is the iterator. The list does not change as you walk through it. Only the iterator's position moves.
Checking which one you have
An iterator must also be iterable. Calling iter() on an iterator returns the same iterator. A list is different: each iter() call gives you a new, independent iterator.
data = [1, 2, 3]
print(iter(data) is data) # False
print(iter(data) is iter(data)) # False: two separate iterators
it = iter(data)
print(iter(it) is it) # True: an iterator returns itselfTwo iterators over one list move independently:
data = ["a", "b", "c"]
first = iter(data)
second = iter(data)
print(next(first)) # a
print(next(first)) # b
print(next(second)) # aWhy the difference matters
An iterable can be looped over many times, because each loop asks for a new iterator. An iterator is used up once. After it raises StopIteration, it stays empty.
it = iter([1, 2, 3])
print(list(it)) # [1, 2, 3]
print(list(it)) # []The second list(it) returns an empty list because the iterator is already at the end. This is the most common iterator mistake, and a later chapter returns to it.
| Property | Iterable | Iterator |
|---|---|---|
| Can be used in a `for` loop | Yes | Yes |
| Works with `iter()` | Returns a new iterator | Returns itself |
| Works with `next()` | No | Yes |
| Can be traversed repeatedly | Usually yes | No, one pass only |
| Holds a position | No | Yes |
Common errors
- Calling
next()directly on a list, tuple, or string. These are iterables, not iterators. - Looping over an iterator twice and expecting the same values the second time.
- Assuming
iter(x)copies the data. It only creates a cursor over the existing object.
Exercise
Given it = iter("hi"), what do next(it), next(it), and a third next(it) produce? Then, what does list(iter("hi")) return if you call it twice on separate iter() calls?
Show answer
The first two calls return 'h' and 'i'. The third raises StopIteration because the iterator is exhausted. Each call to list(iter("hi")) creates a new iterator over the string, so both return ['h', 'i'].
Exercise
A variable x holds an object. iter(x) is x evaluates to True. Is x an iterable, an iterator, or both?
Show answer
Both. Every iterator is also an iterable, and it returns itself from iter(). A plain iterable such as a list would give a new object, so the check would be False.