Iterator Pattern in Modern Languages
What you'll learn: How modern programming languages provide built-in support for the Iterator pattern, making traversal elegant and idiomatic.
Built-In Language Support
You've learned the Iterator pattern's core concept and how to implement custom iterators. Now here's the great news: most modern languages have first-class iterator support baked right in. You rarely need to write iterators from scratch—the language does the heavy lifting.
Instead of manually implementing an iterator interface every time, languages provide standard protocols that collections can follow to become automatically iterable.
Python's __iter__ Protocol
Python uses "magic methods" (dunder methods) to enable iteration:
- Implement
__iter__()to return an iterator object - The iterator implements
__next__()to provide successive elements - When finished,
__next__()raisesStopIteration
Any class with __iter__ works seamlessly with for loops and comprehensions.
Java's Iterable Interface
Java standardizes iteration through the Iterable<T> interface:
- Implement
iterator()to return anIterator<T> - The
IteratorprovideshasNext()andnext()methods - Classes implementing
Iterablework with enhanced for-loops automatically
C#'s IEnumerable
C# provides the IEnumerable<T> interface:
- Implement
GetEnumerator()to return anIEnumerator<T> - The
IEnumeratorhasMoveNext()andCurrentproperty - Works seamlessly with
foreachloops and LINQ queries
The Pattern You Get for Free
Think of these language features as pre-wired electrical outlets. Instead of rewiring every appliance (custom iterator logic), you just plug into the standard socket (implement the language's iterator protocol). The language handles the rest—your collection becomes compatible with loops, comprehensions, and functional operations automatically.
Key Takeaway: Modern languages provide standard iterator interfaces (__iter__, Iterable, IEnumerable) that let you make any collection traversable by implementing one or two methods—the Iterator pattern is built into the language itself.