AlgoViz

Iterator pattern

medium 45 min

The Iterator pattern gives access to the elements of a collection one after the other without showing how they are stored.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:34

Iterator

1:05Reel

Theory

Read or listen first. About 2 min.

What it is

The Iterator pattern is a behavioral design pattern. A collection creates an iterator, an object that holds the position of one walk and offers two operations: is there more, and give me the next element.

The client depends on these operations only. Array, linked list, tree, file or remote server: the loop looks the same.

Most languages have built the pattern in. A for loop over a collection asks for an iterator and calls it until it says stop.

Why it exists

Without it, every client contains knowledge about storage, and storage can not change any more. Two walks at the same time are impossible if the position lives in the collection.

With it, storing and walking are separate responsibilities. New orders such as backwards, shuffled or filtered are new iterators, and the clients stay as they are.

Because an iterator produces elements one at a time, data may be larger than memory, may arrive over a network, or may never end.

A short history

  1. 1994

    The book Design Patterns is published on 31 October and lists Iterator among the behavioral patterns.

  2. JDK 1.0 and 1.2

    Java starts with Enumeration. JDK 1.2 brings java.util.Iterator with shorter names and a safe remove.

  3. 2001

    PEP 234 (30 January) and PEP 255 (18 May) bring iterators and generators to Python.

  4. JDK 1.5

    Iterable arrives in Java, and the for-each loop uses it.

  5. C++20

    Ranges: lazy views such as filter and reverse in the standard library.

Words to know

Iterator
An object for one walk. It holds the position.
Aggregate, iterable
Something that can create iterators.
Exhausted
An iterator that has handed out everything. It stays so.
External iterator
The client pulls the next element.
Internal iterator
The collection calls a function of the client for each element.
Generator
A function with yield that the language turns into an iterator.
Cursor
A position that can be stored or sent.
Fail fast
Stop with an error when the collection changed during the walk.
Snapshot
A walk over the picture at the start.
Weakly consistent
A walk that tolerates changes and may or may not show them.
Lazy
Work is done when an element is asked for, not before.
Lookahead
Reading one element early to answer whether there is more.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 3

Ask. The client asks the collection for an iterator

Understand it

Start here

One way to walk through anything

A playlist, a folder, a friend list and the result of a database query have little in common inside. Yet you want to do the same thing with each of them: take the first element, then the next one, until there are no more. The Iterator pattern gives them all the same two questions. Is there more? and the next one, please.

Noor and the place marker
1234561234Where first?

The wheel knows how its cabins hang. The flag knows how far the walk has come. Noor knows neither.

The five roles

  • Iterator

    The contract of a walk: more, and next. Known as Iterator in Java, IEnumerator in C#.

  • Concrete iterator

    Holds the position and knows one structure: PlaylistIterator, or the iterators inside ArrayList and LinkedList.

  • Aggregate

    The contract of a collection: give me an iterator. Iterable in Java and Python, IEnumerable in C#.

  • Concrete aggregate

    Stores the elements and creates the matching iterator: Playlist, ArrayList, HashSet.

  • Client

    Asks and walks: MusicPlayer, a for loop, a stream. It never sees the storage.

Why

What goes wrong without it

Here is a player that knows too much. It works. Then the playlist changes from an array to a linked list.

Python
class ArrayPlaylist:    def __init__(self, songs):        self.songs = list(songs)          # public, because clients need itclass Node:    def __init__(self, song, after=None):        self.song, self.after = song, afterclass LinkedPlaylist:    def __init__(self, songs):        self.head = None                  # public, because clients need it        for song in reversed(songs):            self.head = Node(song, self.head)titles = ["Bohemian Rhapsody", "Hotel California", "Stairway to Heaven", "Imagine"]p = ArrayPlaylist(titles)i = 0while i < len(p.songs):                   # knows: there is an index    print(p.songs[i])    i += 1q = LinkedPlaylist(titles)node = q.headwhile node is not None:                   # knows: there are nodes    print(node.song)    node = node.after
Run it. The second half prints the same songs with completely different code, and every client has to be rewritten.
Edit and run it in your browser

The design that hurts

MusicPlayer+ playArray(i)+ playNodes(head)ArrayPlaylist+ songs: Song[]

1/3One player, one array

The player reads a public array. It is short and looks harmless.

uses

Both storages are public. Nobody can change them without reading every client.

With an iterator

  • The client knows two questions
  • The same loop for all collections
  • The structure may change freely
  • Many walks at the same time, each with its own position

Without an iterator

  • The client knows the structure inside
  • A different loop for each collection
  • A new structure breaks the clients
  • A shared position allows only one walk at a time

The idea

Take the position out

Two responsibilities are separated. Storing stays in the collection. Walking moves into a new object, which holds the position. The collection only has to say how such an object is made.

The Iterator pattern in general

«interface»Iterator+ hasNext(): bool+ next(): Element

1/5The walk

Two operations. hasNext asks and changes nothing. next hands out one element and moves on.

usesdepends onimplements

The arrow from the concrete iterator to its collection is often to the elements only, or the iterator is a nested class.

One song after the other

After the first answer the playlist is not asked again. The player talks to the iterator.

Contract

The small print of two methods

Two methods look simple, but their promises decide whether a walk is right. Say them aloud in an interview.

What each operation promises

OperationPromiseIf it is broken
hasNextAnswers without moving the position. Ten calls give ten equal answers.Two checks in a row lose an element.
nextHands out one element and moves on by one.An element comes twice or never.
next after the endA clear error: NoSuchElementException in Java, StopIteration in Python, done: true in JavaScript.An empty value that looks like a song.
remove (optional)Removes the element handed out last.The walk and the collection disagree.
reset (optional)Back to the start. A new iterator does the same and is usually clearer.Other code that holds the iterator starts again without knowing.
current (optional)Looks at the element without moving.Nobody knows what it means before the first next.

The same idea in four languages

LanguageThe collection offersThe walk offersThe end
Python__iter____next__StopIteration is raised
Javaiterator() of IterablehasNext(), next()hasNext() is false
TypeScript[Symbol.iterator]()next(){ done: true }
C++begin(), end()*it, ++itit == end()
Java asks first and then takes. Python and JavaScript do both in one step, which is safer when two threads share a source.

What a Python for loop does

You use the pattern in every for loop. The language wrote the client for you.

The life of a walk

A finished iterator stays finished. Songs that are added later belong to a new walk.

Do not mix them up

The collection and the walk

Iterable means: you can get a walk from me, as often as you like. Iterator means: I am one walk, and I am used up at the end. Mixing them up is a common bug, and it makes no noise.

Python
songs = ["Bohemian Rhapsody", "Hotel California", "Stairway to Heaven", "Imagine"]walk = iter(songs)                 # one walkprint("first pass ", len(list(walk)))print("second pass", len(list(walk)))     # 0: the walk is finishedprint("list again ", len(list(songs)))    # the list gives a new walk each timeprint(iter(walk) is walk, iter(songs) is songs)
Run it. The second loop over the iterator sees nothing, and Python raises no error.
Edit and run it in your browser

Four ways to walk

  • External

    The client pulls: next, next, next. It can stop, wait, or walk two collections side by side.

  • Internal

    The collection pushes: songs.forEach(play). Shorter, but the client can not easily pause.

  • Generator

    A function with yield. The language saves the position, including local variables and nested loops.

  • Cursor

    The position is a value you can store and send, such as a page token or a file offset.

Variety

Another order, the same loop

The collection may offer several iterators. Shuffle is not a flag in the player. It is another walk.

Walks over one playlist

WalkWhat it remembersRemark
In orderOne indexThe default: a for loop gets this one
BackwardsOne index that goes downNeeds fast access to the end
ShuffledA shuffled list of indicesCosts one number per song, and each song comes once
Only someThe walk below and a ruleMust look ahead to answer hasNext
EndlessOne index that wraps aroundhasNext is always true if there is a song. Useful for repeat
Python
import randomsongs = ["Bohemian Rhapsody", "Hotel California", "Stairway to Heaven", "Imagine"]def backwards(items):    for i in range(len(items) - 1, -1, -1):        yield items[i]def shuffled(items, rng):    order = list(range(len(items)))    rng.shuffle(order)    for i in order:        yield items[i]def play_all(walk):                # the client    return [song.split()[0] for song in walk]print(play_all(songs))print(play_all(backwards(songs)))mixed = play_all(shuffled(songs, random.Random(7)))print(sorted(mixed) == sorted(play_all(songs)))     # every song exactly once
Three walks as generators. The player does not know which one it got.
Edit and run it in your browser

Choosing

When to write your own

Every language has iterators, so the question is rarely whether to use the pattern. It is whether your class should offer one.

Do I need an iterator class?

Most of the time you delegate. A class is needed when the position itself matters.

Use it when

  • The structure inside should stay hidden
  • Several collections need one loop
  • Several walks run at the same time
  • Several orders are needed: forward, backward, filtered
  • You build a collection of your own, or a source that arrives in pieces

Leave it when

  • A simple list with its built-in loop is enough
  • One private loop in one class is all there is
  • The structure is the point: matrix code with indices
  • A measured hot loop can not pay for a call per element

Clients need all songs of a playlist. What do you offer?

BreaksThe list itself
How
get_songs() returns the internal list.
Limit
Every caller can clear it, and the storage can never change.
Choose when
Never from a public class.
WorksA copy of the list
How
get_songs() returns a new list.
Limit
Safe, but a million songs are copied even if the caller wants one.
Choose when
Small collections, and callers that need a fixed picture.
StrongAn iterator, and a copy on request
How
The class is iterable. Who wants a list writes list(playlist).
Limit
You must say what happens when the playlist changes during a walk.
Choose when
The default.

Gains and costs

GainCost
Storage is hidden and may changeA small class or function per structure
One way to walk, for all collectionsA call per element, sometimes slower than an index
Several walks, several ordersEach walk is an object with memory of its own
Storing and walking are separate jobsChanges during a walk need a rule

Neighbours

Patterns that stand next to it

PatternConnection
Factory methodcreateIterator is one: the collection chooses the class
CompositeA tree of parts is walked by an iterator with a stack
VisitorThe iterator decides the order, the visitor decides what happens to each element
MementoThe position can be saved and restored later
DecoratorA filter or a limit is an iterator wrapped around another iterator
StrategyThe filter rule or the order is a strategy handed to the iterator

Summary

The whole topic in one minute.

Take the position out of the collection. The collection creates iterators, each iterator is one walk, and the client knows only more and next.

Join the protocol of your language. Write generators for ordinary walks and a class when the position matters: a stack for trees, a heap for merging, a key for pages.

Say the policy for changes, never share a walk between threads without one combined step, and close what a walk holds open.

  • Storing and walking are two jobs. The position lives in the iterator.
  • hasNext never moves. next hands out and moves. After the end comes a clear answer.
  • An iterable gives walks. An iterator is one walk and is used up.
  • Each walk gets a new iterator, so walks are independent.
  • Say what happens if the collection changes during the walk.
  • Use the protocol of your language before you write your own.

Sources