Iterator pattern
medium 45 minThe 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
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
1994
The book Design Patterns is published on 31 October and lists Iterator among the behavioral patterns.
JDK 1.0 and 1.2
Java starts with Enumeration. JDK 1.2 brings java.util.Iterator with shorter names and a safe remove.
2001
PEP 234 (30 January) and PEP 255 (18 May) bring iterators and generators to Python.
JDK 1.5
Iterable arrives in Java, and the for-each loop uses it.
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
yieldthat 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.
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.
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
Iteratorin Java,IEnumeratorin C#.Concrete iterator
Holds the position and knows one structure:
PlaylistIterator, or the iterators insideArrayListandLinkedList.Aggregate
The contract of a collection: give me an iterator.
Iterablein Java and Python,IEnumerablein C#.Concrete aggregate
Stores the elements and creates the matching iterator:
Playlist,ArrayList,HashSet.Client
Asks and walks:
MusicPlayer, aforloop, 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.
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.afterThe design that hurts
1/3One player, one array
The player reads a public array. It is short and looks harmless.
uses
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
1/5The walk
Two operations. hasNext asks and changes nothing. next hands out one element and moves on.
usesdepends onimplements
One song after the other
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
| Operation | Promise | If it is broken |
|---|---|---|
hasNext | Answers without moving the position. Ten calls give ten equal answers. | Two checks in a row lose an element. |
next | Hands out one element and moves on by one. | An element comes twice or never. |
next after the end | A 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
| Language | The collection offers | The walk offers | The end |
|---|---|---|---|
| Python | __iter__ | __next__ | StopIteration is raised |
| Java | iterator() of Iterable | hasNext(), next() | hasNext() is false |
| TypeScript | [Symbol.iterator]() | next() | { done: true } |
| C++ | begin(), end() | *it, ++it | it == end() |
What a Python for loop does
for loop. The language wrote the client for you.The life of a 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.
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)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
| Walk | What it remembers | Remark |
|---|---|---|
| In order | One index | The default: a for loop gets this one |
| Backwards | One index that goes down | Needs fast access to the end |
| Shuffled | A shuffled list of indices | Costs one number per song, and each song comes once |
| Only some | The walk below and a rule | Must look ahead to answer hasNext |
| Endless | One index that wraps around | hasNext is always true if there is a song. Useful for repeat |
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 onceChoosing
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?
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
| Gain | Cost |
|---|---|
| Storage is hidden and may change | A small class or function per structure |
| One way to walk, for all collections | A call per element, sometimes slower than an index |
| Several walks, several orders | Each walk is an object with memory of its own |
| Storing and walking are separate jobs | Changes during a walk need a rule |
Neighbours
Patterns that stand next to it
| Pattern | Connection |
|---|---|
| Factory method | createIterator is one: the collection chooses the class |
| Composite | A tree of parts is walked by an iterator with a stack |
| Visitor | The iterator decides the order, the visitor decides what happens to each element |
| Memento | The position can be saved and restored later |
| Decorator | A filter or a limit is an iterator wrapped around another iterator |
| Strategy | The 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.
hasNextnever moves.nexthands 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.