Iterator Pattern in Python
Iterator provides sequential access and lets the collection control how its values are visited.
What is Iterator Pattern?
Iterator provides sequential access and lets the collection control how its values are visited.
Traverse a collection without exposing its internal representation.
When should you use it?
- Solve recurring object-design problems with proven structures.
- Decouple responsibilities so code is easier to extend and test.
- Use shared design vocabulary when discussing architecture with a team.
Example 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)
Expected output
3
2
1
How it works
Countdown implements Python's iteration protocol with __iter__ and a generator.
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.