Python Iterators
Every time you write for x in something, Python uses the iterator protocol behind the scenes. Understanding it explains how for loops work on lists, strings, files and dictionaries alike — and lets you make your own objects loopable.
Iterables vs iterators
| Term | Meaning | Examples |
|---|---|---|
| Iterable | Something you can loop over; iter(obj) gives an iterator |
list, str, tuple, dict, set, range, file |
| Iterator | An object that produces the next value with next(), and remembers where it is |
what iter() returns; generators; map, zip, enumerate objects |
An iterator is a one-way, use-once stream. An iterable is a collection you can ask for a fresh stream as often as you like.
iter() and next()
colors = ["red", "green", "blue"]
it = iter(colors)
print(next(it))
print(next(it))
print(next(it))
try:
next(it)
except StopIteration:
print("StopIteration: nothing left")
print(next(iter(colors))) # a new iterator starts from the beginningred
green
blue
StopIteration: nothing left
red
When an iterator runs out, it raises StopIteration. A for loop catches that for you. In fact, this loop:
for color in colors:
print(color)is roughly equivalent to:
it = iter(colors)
while True:
try:
color = next(it)
except StopIteration:
break
print(color)Iterators are consumed
Once an iterator has handed out a value, it's gone. This catches people out with map, zip and filter objects:
squares = map(lambda n: n * n, [1, 2, 3])
print(list(squares))
print(list(squares)) # already used up!
nums = [1, 2, 3]
print(sum(nums), sum(nums)) # a list can be iterated again and again[1, 4, 9]
[]
6 6
next() also takes a default value to return instead of raising at the end: next(it, None).
Building your own iterator
A class becomes an iterator by implementing two methods:
__iter__()returns the iterator object (usuallyself);__next__()returns the next value or raisesStopIteration.
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(4):
print(n, end=" ")
print()
print(list(Countdown(3)))4 3 2 1
[3, 2, 1]
A reusable iterable
Countdown is consumed after one loop. To make a collection-like object that can be looped repeatedly, let __iter__ return a new iterator each time. The easiest way is to make __iter__ a generator (generators get their own lesson):
class Playlist:
def __init__(self, *songs):
self.songs = list(songs)
def __iter__(self):
for song in self.songs:
yield song
def __len__(self):
return len(self.songs)
p = Playlist("Intro", "Verse", "Outro")
for s in p:
print("Playing", s)
print(len(p), "songs,", "Verse" in p) # `in` works because p is iterable
print(sorted(p))Playing Intro
Playing Verse
Playing Outro
3 songs, True
['Intro', 'Outro', 'Verse']
Once your object is iterable, all of Python's tools work on it: list(), sorted(), sum(), in, unpacking, zip(), enumerate().
Infinite iterators with itertools
An iterator doesn't have to end. The itertools module offers several useful ones; combine them with islice or zip to take a finite piece:
from itertools import count, cycle, islice
print(list(islice(count(10, 5), 4))) # 10, 15, 20, 25
turns = cycle(["X", "O"])
print([next(turns) for _ in range(5)])
for n, day in zip(count(1), ["Mon", "Tue", "Wed"]):
print(n, day)[10, 15, 20, 25]
['X', 'O', 'X', 'O', 'X']
1 Mon
2 Tue
3 Wed
Tip: Iterators are lazy: they compute each value only when asked. That's why
range(10**12)uses almost no memory — it never builds a list.
Test yourself
Which exception signals that an iterator has no more values?
- IndexError
- StopIteration
- EOFError
- IteratorDone
Which two methods make a class an iterator?
- __iter__ and __next__
- __len__ and __getitem__
- __loop__ and __step__
- __init__ and __next__
If m = map(str, [1, 2]), what is list(m) + list(m)?
- ['1', '2', '1', '2']
- ['1', '2']
- []
- An error