Skip to main content

Sign in to CleanKata

Track your progress, earn XP, and unlock every lesson.

By signing in you agree to our Terms of Use and Privacy Policy.

Design Patterns80 XP8 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.

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.

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.

🔧 Some exercises may still have errors. If something seems wrong, use the Feedback button (bottom-right of the page) to report it — it helps us fix it fast.

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

✗ Your version

Iterator: Traversing Collections — CleanKata — CleanKata