Iterables and Iterators · Lecture 03 · 16 min
Iterators and Iterables
An iterable is a collection that hands out a fresh iterator every time you ask; the iterator is the single-use cursor that walks it. Separating the two is what lets you loop over a list again and again.
Two open questions
The previous lesson left two loose ends:
- Why does a
forloop call__iter__first, when for an iterator it just returnsself? - An iterator is exhausted after one pass. Do we really have to rebuild the object every time we want to loop again?
Both have the same answer. Here’s the problem in its simplest form:
class Cities:
def __init__(self):
self._cities = ['Paris', 'Berlin', 'Rome', 'Madrid', 'London']
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index >= len(self._cities):
raise StopIteration
item = self._cities[self._index]
self._index += 1
return item
cities = Cities()
print(list(cities))
print(list(cities)) # exhaustedTo loop twice we’d have to call Cities() again, rebuilding the data just to reset one integer. The data and the position in the data are tangled together in one object. Let’s pull them apart.
Splitting the data from the cursor
First, a class that only holds the data:
class Cities:
def __init__(self):
self._cities = ['New York', 'Newark', 'New Delhi', 'Newcastle']
def __len__(self):
return len(self._cities)Then a separate class whose only job is to walk an existing Cities object. It keeps a reference to the data and its own index:
class CityIterator:
def __init__(self, city_obj):
self._city_obj = city_obj
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index >= len(self._city_obj):
raise StopIteration
item = self._city_obj._cities[self._index]
self._index += 1
return item
cities = Cities() # data built once
for city in CityIterator(cities): # one walk
print(city)
print([c.upper() for c in CityIterator(cities)]) # another, independent walkMuch better: the data is created once and each CityIterator is a cheap cursor over it. But now we must remember to create an iterator by hand, and the cities object itself can’t be looped over:
try:
for city in cities:
print(city)
except TypeError as ex:
print('TypeError:', ex)The iterable protocol
This is where that first __iter__ call pays off. An iterable is an object whose __iter__ method returns a new iterator over its data. When a for loop starts, it calls iter(obj) and loops over whatever comes back. So all Cities needs is an __iter__ that builds a CityIterator:
class Cities:
def __init__(self):
self._cities = ['New York', 'Newark', 'New Delhi', 'Newcastle']
def __len__(self):
return len(self._cities)
def __iter__(self):
print('Cities.__iter__: making a new iterator')
return CityIterator(self)
cities = Cities()
for city in cities:
print(city)
for city in cities: # works again!
print(city)Every loop asks the iterable for a fresh iterator, so every loop starts at the beginning. The same happens with any consumer:
print(sorted(cities, reverse=True))
it_1 = iter(cities)
it_2 = iter(cities)
print(it_1 is it_2)
print(next(it_1), next(it_1), next(it_2)) # independent positionsThis is the core picture of the whole section:
iter() call. Each iterator refers back to the same data (grey arrow, drawn for it_1) and keeps its own position; exhausting one doesn't affect the other or the iterable.Iterable vs iterator, side by side
| Iterable | Iterator | |
|---|---|---|
| Must implement | __iter__ |
__iter__ and __next__ |
__iter__ returns |
a new iterator | itself |
Can you call next() on it? |
No | Yes |
| Loop over it twice? | Yes, each loop starts fresh | No, the second loop is empty |
| Holds | the data (or a recipe for it) | a position in the data |
| Examples | list, str, dict, set, range |
iter([1, 2]), zip(...), enumerate(...), files |
Notice the asymmetry: every iterator is also an iterable (its __iter__ returns something you can call next() on, namely itself). That’s precisely why iterators must implement __iter__: so you can pass an iterator anywhere an iterable is expected, including a for loop. But an iterator is a degenerate iterable: it can only be iterated once.
For an object obj that you can iterate, iter(obj) is obj is True for an iterator and False for a re-iterable collection. You’ll use this test later to defend functions against being handed an iterator.
Keeping the iterator private
Since the iterator only makes sense together with its iterable, it’s common to nest the iterator class inside the iterable:
del CityIterator # make sure the global one isn't used
class Cities:
def __init__(self):
self._cities = ['New York', 'Newark', 'New Delhi', 'Newcastle']
def __len__(self):
return len(self._cities)
def __iter__(self):
return self.CityIterator(self)
class CityIterator:
def __init__(self, city_obj):
self._city_obj = city_obj
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index >= len(self._city_obj):
raise StopIteration
item = self._city_obj._cities[self._index]
self._index += 1
return item
cities = Cities()
print(list(enumerate(cities)))
print(type(iter(cities)).__qualname__)Iterable and sequence
Cities is iterable but it isn’t a sequence: it has len() but no indexing.
print(len(cities))
try:
cities[1]
except TypeError as ex:
print('TypeError:', ex)A class can implement both protocols. If it has __iter__ and __getitem__, which one does a for loop use?
class Cities:
def __init__(self):
self._cities = ['New York', 'Newark', 'New Delhi', 'Newcastle']
def __len__(self):
return len(self._cities)
def __getitem__(self, s):
print('__getitem__ called')
return self._cities[s]
def __iter__(self):
print('__iter__ called')
return iter(self._cities) # a list iterator does the walking for us
cities = Cities()
print(cities[0])
for city in cities:
print(city)__iter__ wins. Python only falls back to __getitem__ if there’s no __iter__ (more on that fallback in a later lesson). Indexing and slicing, of course, still need __getitem__. (Returning iter(self._cities) is a shortcut called delegation, which also gets its own lesson.)
Built-in collections work exactly the same way
Lists, sets, dicts and strings are all iterables, not iterators. Each has an __iter__ that returns a dedicated iterator type:
l = [1, 2, 3]
iter_l = iter(l)
print(type(iter_l))
print(next(iter_l), next(iter_l), next(iter_l))
try:
next(iter_l)
except StopIteration:
print('StopIteration, just like ours')print('list has __iter__:', '__iter__' in dir(l), '| __next__:', '__next__' in dir(l))
print('list_iterator has __iter__:', '__iter__' in dir(iter_l), '| __next__:', '__next__' in dir(iter_l))
print(iter(iter_l) is iter_l, iter(l) is l)
print(type(iter({1, 2, 3})), '__getitem__' in dir(set))A set has no __getitem__, so it can only be iterated through its iterator. And a dictionary? Its iterator yields the keys; use the .values() and .items() views for the rest:
d = dict(a=1, b=2, c=3)
print(next(iter(d)))
print(next(iter(d.values())))
print(next(iter(d.items())))Key takeaways
- An iterable implements
__iter__, which returns a new iterator each time. An iterator implements__iter__(returningself) and__next__. for(and every other consumer) first callsiter(obj), then callsnext()on the result. That’s why a list can be looped over repeatedly: each loop gets a fresh iterator.- Iterators are iterables too, but single-use ones. Iterables can’t be passed to
next(). - Keep the data in the iterable and the position in the iterator. Nesting the iterator class inside the iterable keeps it private.
- If a class has both
__iter__and__getitem__, iteration uses__iter__. - Built-in collections follow the same pattern:
list→list_iterator,dict→ keys iterator, and so on.