Python Design Patterns

Iterator Pattern in Python

Let any collection work in a for loop by implementing __iter__ and __next__, or by writing a generator.

  • Advanced
  • 2 min read
  • 1 runnable example
What you'll learn
  • The iterator protocol
  • StopIteration
  • Generators with yield
for n in Countdown(3)
  1. 1next() → 3
  2. 2next() → 2
  3. 3next() → 1
  4. 4StopIterationthe loop ends

Values one at a time

The problem

Code that loops over a collection should not need to know how it is stored: a list, a tree, a file or values computed on the fly. Python's for loop works with any object that follows the iteration protocol.

Think of it like this

An iterator is like a ticket dispenser at a deli counter. Each pull gives you the next number. You do not see how the numbers are stored inside; you just keep pulling until the dispenser says it is empty.

From a ticket dispenser to code
for number in Countdown(3):🎫 Pull tickets until it is empty
__iter__⚙️ The dispenser's mechanism
yield current➡️ Hand out the next number
while current > 0:🏁 Stop when no numbers are left
Values come one at a time; the storage stays hidden.
In one sentence

The Iterator pattern provides sequential access to the elements of a collection without exposing how they are stored; in Python, an object is iterable when its __iter__ method returns an iterator.

Key points

  1. Countdown(3) stores only the starting number.
  2. __iter__ is what the for loop calls to start iterating.
  3. Because it contains yield, __iter__ returns a generator that produces 3, 2 and 1 one at a time.
  4. The loop stops automatically when the generator finishes.

When should you use it?

  • Making your own collections work with for, list(), sum() and comprehensions.
  • Producing values lazily instead of building a full list in memory.
  • Hiding how data is stored or calculated.

When not to use it

  • A simple list or range already does the job.
  • You need random access by position: an iterator only goes forward.

Example code

Run code →
main.py
class Countdown:
    # Iterator: traverse values without exposing representation details.
    def __init__(self, start): self.start = start

    def __iter__(self):
        # Yield values without exposing collection storage.
        current = self.start
        while current > 0:
            yield current
            current -= 1


for number in Countdown(3):
    print(number)
Get a Run button for this example

Result of running the code

3
2
1

Code explanation

A for loop calls __iter__ on Countdown(3) to get something it can step through. Because __iter__ uses yield, Python turns it into a generator that pauses after each value and resumes on the next request. It yields 3, 2 and 1, and when the while loop ends the generator finishes and the for loop stops.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Replace the sample domain while preserving the pattern structure.
  2. Compare the pattern with a simpler implementation and explain the tradeoff.
  3. Write tests for each participant before adding another implementation.
Run in the Python compiler →

Common mistakes

Returning a list from __iter__

__iter__ must return an iterator, not a list.

Problem
def __iter__(self):
    return [3, 2, 1]  # TypeError
Fix
def __iter__(self):
    return iter([3, 2, 1])

Finished this lesson?

Mark it as learned to track your progress.

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges