intermediate

Iterators in Python

6 min read

Overview

An Iterator is an object that allows you to traverse through a sequence of data one element at a time. In simple words, an iterator remembers its current position during iteration and returns the next item when asked.

Learning Objectives

  • Learn what makes an object iterable vs an iterator.
  • Use iter() to obtain an iterator and next() to fetch elements.
  • Create custom iterator classes by implementing __iter__() and __next__().

Concept Explanation

In Python:

  1. Iterable: Any object you can loop over using a for loop (like a list, tuple, str, or dict). An iterable produces an iterator when passed to iter().
  2. Iterator: An object that implements the iterator protocol with two magic methods:
    • __iter__(): Returns the iterator object itself.
    • __next__(): Returns the next value in the sequence. When no more items remain, it raises a StopIteration exception.
text
Iterable Object (e.g. [10, 20, 30])  --->  iter()  --->  Iterator Object  --->  next()  --->  10, 20, 30

Code Examples

Example 1 — Basic Manual Iteration

Using iter() and next() manually to step through a list:

python
numbers = [10, 20, 30]

# Obtain an iterator object from the list
num_iter = iter(numbers)

print(next(num_iter)) # 10
print(next(num_iter)) # 20
print(next(num_iter)) # 30

# Calling next() again raises StopIteration exception
try:
    print(next(num_iter))
except StopIteration:
    print("Reached the end of the sequence.")

Example 2 — Building a Custom Counter Iterator

Creating a class that acts as a custom iterator:

python
class Counter:
    def __init__(self, start, end):
        self.current = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.current > self.end:
            raise StopIteration
        val = self.current
        self.current += 1
        return val

counter = Counter(1, 3)
for num in counter:
    print(f"Count: {num}")

Visual Flow

The following execution flow represents step-by-step iterator evaluation:

⚡ Visual Execution Flow
Pass Iterable to iter()Call next() on IteratorYield Current Value & Move PointerRaise StopIteration at End

Common Mistakes

  • Exhausted Iterators: Trying to loop over an iterator a second time without recreating it. Iterators can only be consumed once.
  • Forgetting return self in __iter__(): Custom iterators must return self inside __iter__().

Best Practices

  • Use built-in Python for loops or generator expressions for simple iterations instead of writing manual __next__() loops.