Advertisement
❮ Previous: Python For Loops & Range Next: Python Generators & Yield ❯

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:


Advertisement

2. The Built-in Functions: iter() and next()

Python exposes these protocols directly via two built-in functions:

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

Try this code ❯


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)

Try this code ❯

Python executes the following steps behind the scenes:

  1. Passes the list to iter() to obtain an iterator object.
  2. Repeatedly calls next() on the iterator inside an invisible try...except block.
  3. Catches the StopIteration exception 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

Try this code ❯


Advertisement

5. Why Iterators Matter

❮ Previous: Python For Loops & Range Next: Python Generators & Yield ❯
Advertisement