Lesson 5: Iterables, Iterators and the Iterator Protocol
Every for loop you have ever written in Python hides a small piece of machinery. When you write for word in words:, Python does not magically know how to walk through the list. It asks the list for an iterator — an object whose job is to hand out items one at a time — and then repeatedly asks that iterator for the next item until the iterator says there are no more. Understanding this machinery matters because it explains how loops, unpacking, and many built-in functions actually work, and because it lets you build your own iterable objects.
The distinction is precise. An iterable is any object you can loop over: it defines __iter__, which returns an iterator. An iterator is an object that defines __next__, which returns the next item or raises StopIteration when the items run out — and whose __iter__ returns itself. A list is an iterable but not an iterator: you can loop over it as many times as you like, because each loop creates a fresh iterator. A file object, by contrast, is its own iterator: once you have read through it, it is exhausted, and looping again gives you nothing until you reopen it.
words = ["alpha", "beta", "gamma"]
it = iter(words) # ask the list for an iterator
print(next(it)) # alpha
print(next(it)) # beta
print(next(it)) # gamma
try:
print(next(it))
except StopIteration:
print("no more items") # the iterator is exhausted
for w in words: # a for loop does exactly this, behind the scenes
print(w)
Building your own iterable
You can make your own classes iterable by defining __iter__. The example below is a Countdown class: calling iter() on it returns a small helper object that counts down from the starting number, raising StopIteration at zero. Writing the iterator as a separate class keeps the two jobs apart — the countdown holds the settings, the iterator holds the current position — and that separation is exactly how Python's own containers are built. Notice that a fresh iterator starts from the top every time, so you can loop over the same countdown twice.
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
return CountdownIterator(self.start)
class CountdownIterator:
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, 2, 1
One more thing worth knowing: many Python features are just the iterator protocol in disguise. Unpacking (a, b = pair), list(), sum(), max(), and the * operator in a function call all consume iterators. That is why they work on lists, tuples, sets, dictionaries, files, and your own classes alike — anything that follows the protocol plugs in for free. The next lessons will show how generators make writing iterators far easier than writing a whole class.
Going further
The iterator protocol explains several behaviours that otherwise look mysterious. When you loop over a dictionary, you iterate over its keys; when you loop over a file, you iterate over its lines; when you unpack a value with a, b = pair, Python asks the pair for an iterator and pulls exactly two items. Even zip() is just iterators working together: it pulls one item from each of its inputs at a time, and stops as soon as the shortest input runs out. Once you see the protocol underneath, these features stop being separate rules and become one idea applied everywhere.
A common question is whether you should write your own iterator class or use a generator instead. The honest answer is that generators, which you meet in Lesson 7, are almost always the better choice: they do the same job with far less code, and they handle the StopIteration bookkeeping for you. The iterator class is still worth knowing, because it shows you what a generator is doing behind the scenes, and because some objects — a deck of cards that can be shuffled, or a collection that can be iterated in several different orders — genuinely need the control that a class provides.
To see the protocol in action, try writing a for loop over a dictionary and printing what comes out: you will get the keys, one at a time, because a dictionary's __iter__ yields keys. Then try list(my_dict), which does the same thing through the same protocol, and for key, value in my_dict.items(), which iterates over pairs instead. Each of these is the same machinery with a different iterator. The exercise takes two minutes, and it replaces three separate facts to memorise with one idea that explains all of them.
Key Terms
- Iterable
- An object you can loop over; it defines __iter__, which returns an iterator.
- Iterator
- An object that hands out items one at a time through __next__, raising StopIteration when done.
- __iter__
- The special method that returns an iterator for an object; for an iterator it returns itself.
- __next__
- The special method that returns the next item from an iterator.
- StopIteration
- The exception an iterator raises when it has no more items; a for loop catches it and stops.
- iter()
- The built-in that asks an iterable for its iterator.
- next()
- The built-in that asks an iterator for its next item.
Discussion Questions
- Why can you loop over a list twice, but reading through a file a second time gives you nothing? What is different about the two objects?
- Why does __iter__ on an iterator return self, instead of creating a new iterator?
- Where else have you used the iterator protocol without realising it — unpacking, sum(), list()? Pick one and explain how it fits.
Practice Questions
- Is a list an iterator? Explain.
- What does
next()do when an iterator is exhausted? - Why does the
Countdownexample use two classes instead of one? - Write code that manually pulls the first two items from
iter([10, 20, 30]). - Name two built-in functions that consume iterators.
Show answers
- No — a list is an iterable, not an iterator. A list defines __iter__ but not __next__; each loop asks it for a fresh iterator.
- It raises StopIteration. A for loop catches that exception silently and ends the loop.
- To separate the settings from the current position. The countdown holds the start value; each iterator tracks its own progress, so two loops do not interfere.
it = iter([10, 20, 30]); print(next(it)); print(next(it))— prints 10 then 20. iter() builds the iterator and next() pulls items one at a time.- Any two of: list(), sum(), max(), min(), sorted(), tuple(), set(). They all work by pulling items through the iterator protocol, which is why they accept any iterable.