Python Iterators & Iterable Protocol
Understanding Python Iterators & the Iterable Protocol
In Python, iteration is the fundamental mechanism used to traverse collections (like lists, dictionaries, and strings). To understand how loops (for, while) and data pipelines actually function under the hood, you need to master the Iterable Protocol and the Iterator Protocol.
1. Core Concepts: Iterable vs. Iterator
Before looking at the code, it is vital to distinguish between the two:
- Iterable: An object that has a
__iter__()method (or supports the sequence protocol via__getitem__()) which returns an iterator. Examples includelist,str,dict,tuple, andset. An iterable can be looped over repeatedly. - Iterator: An object that represents a stream of data and remembers its position during traversal. It implements two methods:
__iter__(): Returns the iterator object itself.__next__(): Returns the next item from the sequence. When items are exhausted, it raises aStopIterationexception.
Advertisement
2. The Built-in Functions: iter() and next()
Python exposes these protocols directly via two built-in functions:
iter(obj): Invokes the__iter__()method on an iterable to produce an iterator.next(iterator): Invokes the__next__()method on an iterator to fetch the next value.
Example: Manual Iteration
# A list is an iterable, but it is NOT an iterator itself
numbers = [10, 20, 30]
# 1. Obtain an iterator from the iterable
iterator = iter(numbers)
# 2. Fetch items manually using next()
print(next(iterator)) # Output: 10
print(next(iterator)) # Output: 20
print(next(iterator)) # Output: 30
# Calling next() when no items remain raises StopIteration
# print(next(iterator)) # Raises StopIteration
Advertisement
3. How a for Loop Works Under the Hood
When you write a standard for loop in Python:
for item in [1, 2, 3]:
print(item)
Python executes the following steps behind the scenes:
- Passes the list to
iter()to obtain an iterator object. - Repeatedly calls
next()on the iterator inside an invisibletry...exceptblock. - Catches the
StopIterationexception automatically to terminate the loop cleanly.
Advertisement
4. Building a Custom Iterator
To build a custom iterator object, you implement a class containing both __iter__() and __next__().
Example: Countdown Iterator
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
# An iterator must return itself
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
val = self.current
self.current -= 1
return val
# Using the custom iterator
counter = Countdown(3)
for num in counter:
print(num)
# Output:
# 3
# 2
# 1
Advertisement
5. Why Iterators Matter
- Memory Efficiency (Lazy Evaluation): Iterators generate and return items on demand (
next()) rather than storing an entire collection in memory at once. This makes them essential for streaming large files or infinite data sequences.