Iterator Pattern in Python
Let any collection work in a for loop by implementing __iter__ and __next__, or by writing a generator.
- The iterator protocol
- StopIteration
- Generators with yield
- 1
next() → 3 - 2
next() → 2 - 3
next() → 1 - 4
StopIterationthe 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.
for number in Countdown(3):🎫 Pull tickets until it is empty__iter__⚙️ The dispenser's mechanismyield current➡️ Hand out the next numberwhile current > 0:🏁 Stop when no numbers are leftThe 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
Countdown(3)stores only the starting number.__iter__is what theforloop calls to start iterating.- Because it contains
yield,__iter__returns a generator that produces 3, 2 and 1 one at a time. - 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
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)
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.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.
Common mistakes
Returning a list from __iter__
__iter__ must return an iterator, not a list.
def __iter__(self):
return [3, 2, 1] # TypeError
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