Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 57 ยท Behavioral Patterns

Iterator

Learn the Iterator design pattern: visit the items of a collection one at a time without exposing its structure. Includes JS generators, Python __iter__ and Java Iterable.

The Iterator pattern gives you a standard way to visit the items of a collection one at a time, without knowing how the collection stores them. A list may be an array, a tree, a linked list, a database cursor or a function that computes values on demand. The loop that reads them should not care.

Without the pattern, every caller has to learn the internal layout: "this one is an array, so use an index; that one is a tree, so write a recursive walk." With it, every collection offers the same small contract (give me the next item, or tell me you are finished), and one for loop works everywhere. Today the pattern is built into almost every language, which is why you rarely write the classic version by hand.

One loop, any collection

Aggregate The collection that can create an iterator.
Iterator Remembers where you are and gives the next item.
Client Just loops; knows nothing about the structure.

The cursor lives in the iterator, not in the collection.

1 / 2

The structure

There are two roles. The iterable (or aggregate) is the collection; it has a method that creates an iterator. The iterator has two operations: is there another item? and give me the next one. Because the position is stored in the iterator, you can run several iterations over the same collection at the same time.

classDiagram
    class Iterable {
        <<interface>>
        +iterator() Iterator
    }
    class Iterator {
        <<interface>>
        +hasNext() bool
        +next() item
    }
    class Playlist
    class PlaylistIterator
    Iterable <|.. Playlist
    Iterator <|.. PlaylistIterator
    Playlist ..> PlaylistIterator : creates

Playlist hides how songs are stored; its iterator walks them.

Iterators in JavaScript

JavaScript's contract is small. An object is iterable if it has a method named [Symbol.iterator]() that returns an iterator: an object with a next() method returning { value, done }. Once an object follows the contract, for...of, spread ([...x]), destructuring and Array.from all work on it.

Writing next() by hand is the classic form. Generators (function* with yield) let the language write the iterator for you: the function pauses at each yield and resumes on the next request, and the "current position" is simply where the function is paused.

JS A tree walked by a hand-written iterator and by generators

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The tree never reveals that it stores children arrays. A caller who wants the values in depth-first order says so, and a caller who wants breadth-first order calls a different generator. The two cursors at the end advance independently because each lives in its own iterator.

Lazy and infinite sequences

A generator produces the next value only when asked, which makes it lazy. That allows sequences that could never fit in memory, such as "all Fibonacci numbers", and it lets you stop early.

JS Lazy generators and early exit

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Each helper is itself a small iterator that wraps another one, so they compose like a pipeline. Notice that break calls the iterator's return() method, which is why the finally block runs: iterators can release resources (files, connections) when you stop early.

Iterators in Python

Python's version has the same two roles. An iterable defines __iter__() returning an iterator; an iterator defines __next__(), which returns the next item or raises StopIteration. And, as in JavaScript, a generator function with yield is the short way. The class below stores its songs in a dictionary-like structure but loops like a list.

Python Python __iter__, __next__ and yield

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A collection that is its own iterator (one with __next__ directly on it) can be looped over only once, because the position is stored in the collection. Returning a fresh iterator from __iter__, as Playlist does, allows repeated and nested loops.

Java's Iterable and Iterator

Java makes the roles explicit with two interfaces. A class that implements Iterable<T> can be used in an enhanced for loop. This snippet is read-only; the site cannot compile it in the page, but it is the whole contract:

Java
class Playlist implements Iterable<String> {
    private final List<String> songs = new ArrayList<>();
    void add(String song) { songs.add(song); }

    @Override
    public Iterator<String> iterator() {
        return new Iterator<>() {
            private int index = 0;
            @Override public boolean hasNext() { return index < songs.size(); }
            @Override public String next() { return songs.get(index++); }
        };
    }
}

// for (String song : playlist) { ... }

C++ uses iterators too (begin() and end(), with ++ and *), and the standard library's range-based for loop relies on them. Java's Iterator also has an optional remove(); most built-in collections throw ConcurrentModificationException if you change them while iterating.

Pitfalls and design notes

  • Changing a collection while iterating is the most common bug. Some collections detect it and fail fast; others silently skip or repeat items. Iterate over a copy or collect changes and apply them afterwards.
  • One-shot iterators. A generator or iterator is used up after one pass. Calling [...gen] twice on the same generator object gives an empty second result.
  • Hidden cost. An iterator over a remote source or a lazily computed sequence may be slow per item. Do not assume iteration is free.
  • External vs internal. Here the caller drives with next() (external iteration). Methods like forEach and map run the loop for you (internal iteration). Prefer the simpler one that fits.

Iterator pairs naturally with Composite, because a tree needs a traversal, and with Visitor, which applies an operation to each node during a walk. If you hand out different traversal orders, you are using a small Strategy.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the Iterator pattern keep the cursor in the iterator rather than in the collection?

    When the position lives in a separate iterator, each loop gets its own cursor, so nested or simultaneous loops over one collection do not interfere.
  2. 2. In JavaScript, what must next() return for an iterator?

    The protocol is an object like { value, done }, where done becomes true when the sequence is finished.
  3. 3. What makes a generator 'lazy'?

    A generator pauses at each yield and resumes on demand, so it can represent very long or even infinite sequences.
  4. 4. How does a Python iterator signal that there are no more items?

    The for loop calls next repeatedly and stops when StopIteration is raised. Returning None would be treated as a normal item.
  5. 5. What is a common bug when iterating over a collection?

    Mutating the collection during iteration can skip items, repeat them or throw an error such as ConcurrentModificationException. Iterate a copy or apply changes afterwards.

Summary

  • Iterator lets you visit a collection's items one at a time without knowing its internal structure.
  • The iterator stores the position, so several independent loops can run on one collection.
  • JavaScript uses [Symbol.iterator]() and next(); generators with yield write the iterator for you.
  • Python uses __iter__ and __next__ (raising StopIteration), or yield; Java uses Iterable and Iterator.
  • Generators are lazy, compose like pipelines, and can run cleanup when you stop early.
  • Do not modify a collection while iterating it, and remember that iterators are usually single use.

Next lesson: Chain of Responsibility.