Course contentsShow
← Software Engineering
Lesson 297 of 1,9339. Behavioral Design PatternsFree lesson

Iterator Pattern in Modern Languages

Explore language-level iterator support like Python's __iter__, Java's Iterable, and C#'s IEnumerable.

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__() raises StopIteration

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 an Iterator<T>
  • The Iterator provides hasNext() and next() methods
  • Classes implementing Iterable work with enhanced for-loops automatically

C#'s IEnumerable

C# provides the IEnumerable<T> interface:

  • Implement GetEnumerator() to return an IEnumerator<T>
  • The IEnumerator has MoveNext() and Current property
  • Works seamlessly with foreach loops 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.