Python Iterators and the Iteration Protocol
Master Python's iteration protocol under the hood. Understand iterables vs iterators, __iter__ and __next__ dunder methods, StopIteration, and custom iterator classes.
Ever since Stage 4, you have used for loops to iterate through sequences:
for item in ["apple", "banana", "cherry"]:
print(item)
It looks simple and magical. But what actually happens inside Pythonโs engine when that loop executes?
- How does Python know where it currently is in the list?
- How does it know when the list runs out of items?
- Why can Python loop over lists, strings, dictionaries, sets, and file handles using the exact same
forloop syntax?
The mechanism powering all repetition in Python is the Iteration Protocol.
1. Iterable vs Iterator: The Core Distinction
Understanding the difference between an Iterable and an Iterator is one of the hallmarks of an advanced Python developer:
ITERABLE (The Book) ITERATOR (The Bookmark)
โโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ["Alice", "Bob", "Dan"]โ โโiter()โโบ โ Current position: 0 โ
โ โ โ next() โโโบ "Alice" โ
โ Can be looped over. โ โ next() โโโบ "Bob" โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโ
- An Iterable: Any object capable of returning its members one at a time. It is a data container (e.g.
list,tuple,dict,str,set). It implements the__iter__()method. - An Iterator: A stateful object representing an active stream of data. It remembers its current position and produces the next value upon request. It implements both
__iter__()and__next__().
2. The Built-in iter() and next() Functions
You can step through any iterable manually using the built-in iter() and next() functions:
fruits = ["Apple", "Banana", "Cherry"]
# 1. Obtain an iterator from the iterable list:
fruit_stream = iter(fruits)
print("Type:", type(fruit_stream)) # <class 'list_iterator'>
# 2. Request values one by one:
print(next(fruit_stream)) # Apple
print(next(fruit_stream)) # Banana
print(next(fruit_stream)) # Cherry
# 3. What happens when the iterator is exhausted?
# print(next(fruit_stream))
# StopIteration!
When an iterator runs out of items, it raises the StopIteration exception. This is not an error; it is the official signal that the sequence is complete!
Safe Fallback Default
You can supply a default fallback value to next(iterator, default) to prevent StopIteration from being raised:
item = next(fruit_stream, "NO_MORE_FRUITS")
print(item) # NO_MORE_FRUITS
3. How the for Loop Actually Works
Now we can pull back the curtain on Pythonโs for loop. When you write:
for item in my_list:
process(item)
Python executes this exact while loop behind the scenes:
# The internal mechanics of a for loop in pure Python:
iterator = iter(my_list) # 1. Get the iterator
while True:
try:
item = next(iterator) # 2. Get next item
process(item) # 3. Run loop body
except StopIteration: # 4. Catch the end signal
break # 5. Exit cleanly!
4. Building a Custom Iterator Class
To make a custom class an iterator, you must implement the two methods of the Iteration Protocol:
__iter__(self): Must return the iterator object itself (return self).__next__(self): Must return the next value, or raiseStopIterationwhen finished.
class Countdown:
"""A custom iterator that counts down from start to 1."""
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
# Using our custom iterator in a standard for loop:
print("Launching in:")
for sec in Countdown(3):
print(f" {sec}...")
print("Ignition!")
Output:
Launching in:
3...
2...
1...
Ignition!
Summary & Whatโs Next
- An iterable is any object that can be looped over (implements
__iter__). - An iterator is the stream object that yields items on demand via
__next__. - Exhausted iterators raise
StopIterationto signal completion. - Pythonโs
forloop is simply syntactic sugar foriter(),next(), and catchingStopIteration.
Writing full iterator classes with __iter__, __next__, and manual state tracking can be verbose. What if you could write a normal function that pauses and resumes automatically? Learn about generators.