Skip to main content
Design Patterns 80 XP · 8 min

Iterator: Traversing Collections

Traverse elements of any collection without exposing its internal structure — the client never needs to know if it's a list, tree, or graph.

Showing
Ad (728×90)

Why this matters

When client code reaches into a collection's internals — accessing ._items[i] directly — it couples itself to the implementation. Swap a list for a tree and every client breaks. The Iterator pattern gives client code a single, uniform way to traverse any collection: just ask for the next element. The collection controls how it walks itself; the client never sees inside.

The problem

Bad

The solution

Good

Built into the language

Python's for x in obj calls __iter__ then repeatedly calls __next__ — Iterator is the protocol. TypeScript's for...of calls Symbol.iterator. Generators in both languages are Iterator factories. Any time you've written for x in something, you've used Iterator.

Key takeaway

Iterator decouples traversal from collection — you can change the internal structure or add a new traversal order without touching client code.

Done with this lesson?

Mark it complete to earn XP and track your progress.