Iterator gives code a way to go through the elements of a collection one at a time without knowing how the collection stores them. The collection hands out an iterator object, and the iterator keeps the position (the cursor), so several walks can run at once and the collection can change its internal structure without breaking the code that walks it. It is so useful that every mainstream language builds it in: for...of in JavaScript, for x in in Python, the for-each loop in Java and range-based for in C++ all run on iterators.
Think of it like
Bookmarks in a shared book
Three people are reading the same book, each with their own bookmark. Each reader only knows one move: open at my bookmark, read the next page, move the bookmark. Nobody cares whether the book is bound, a ring binder or an e-reader that loads chapters on demand, and one reader moving their bookmark never loses another reader's place. The book is the collection, each bookmark is an iterator holding its own cursor, and "next page" is next().
The problem
A music app has a Playlist of songs, and two pieces of code read it: a Player that plays one song at a time, and a Preview that lists the whole playlist. The quickest version makes the songs a public array and lets each client index it. This is the Before version in the visualizer above.
class Playlist {
constructor(public songs: string[]) {}
}
class Player {
private index = 0;
constructor(private list: Playlist) {}
playNext(): string {
const songs = this.list.songs;
if (this.index >= songs.length) return "";
return songs[this.index++];
}
}
class Preview {
show(list: Playlist): string {
const out: string[] = [];
for (let i = 0; i < list.songs.length; i++) {
out.push(list.songs[i]);
}
return out.join(", ");
}
}It works, and with one array and two clients it even looks simpler than any pattern. The cost shows up when the collection changes:
- The storage is a public contract. Every client wrote
list.songs[i], sosongsmust stay an array forever. Storing songs in pages (as a long playlist is fetched from a server), in a linked list or in a tree means finding and rewriting every loop in the code base. - The walking logic is copied. Bounds checks, "where is the next element" and "are we done" are written again in every client. With pages, each copy needs a two-part cursor and a page turn, and one copy with an off-by-one bug is enough.
- Every client must know every traversal. A tree has several orders (in-order, level-order); a playlist may need shuffle or skip rules. Without an iterator, each client re-implements the one it needs.
- Encapsulation is gone. With
songspublic, any client can also push, remove or reorder songs, so the playlist cannot protect its own invariants.
The pattern
Intent: provide a way to access the elements of a collection sequentially without exposing its underlying representation. The traversal state lives in a separate iterator object, not in the collection and not in the client.
- Iterator (
Iterator<T>) - The interface for walking:
hasNext()answers "is there another element?" andnext()returns it and moves the cursor. Clients depend only on this. - Concrete iterator (
PlaylistIterator) - One traversal over one kind of collection. It holds the cursor (
index, orpageandpos, or a stack for a tree) and is the only class besides the collection that knows the storage. - Aggregate, or iterable (
Playlist) - The collection. It keeps its storage private and offers a factory method,
iterator(), that returns a new concrete iterator positioned at the start. Java calls this interfaceIterable. - Client (
Player,Preview) - Code that asks for an iterator and loops with
hasNext()andnext(). It never learns whether the elements live in an array, pages, nodes or a database.
iterator() is a Factory Method: the collection decides which iterator class to create, and the client receives it typed as the interface. Because each call returns a new iterator with its own cursor, two clients can walk the same collection at different positions without disturbing each other. The concrete iterator is tightly coupled to its collection by design (in Java it is usually a private inner class), which is fine: the two live in the same file and change together.
What the visualizer shows
Press Play in the visualizer at the top of the page, or step with the arrow buttons. It really runs the classes in the code panel; the running line is highlighted and the caption explains each step.
- Class diagram: when the player or the preview calls
next(), theIteratorinterface lights up in violet (the declared type) whilePlaylistIteratorruns in amber.PlayerandPreviewonly have arrows toIterator(andPreviewtoPlaylistforiterator()), never to the array. - Objects at runtime: the strongest moment.
it : PlaylistIteratorholdsindex = 1after the player plays"Sun". Then the preview asks for its own iterator,it2, and you watchit2.indexgo 0, 1, 2, 3 whileit.indexstays at 1. Two cursors, one collection. - Sequence of calls: the repeating rhythm of external iteration:
hasNext()→true,next()→ a song, untilhasNext()answersfalse.
Before / With Iterator switches to the version where clients index list.songs themselves: notice that the playlist never receives a message. Store in pages applies the change request (songs stored as [["Sun", "Sea"], ["Sky"]]): changed classes get a badge, and the Change request panel counts what each version had to edit.
Walkthrough
- 1
Create the collection
new Playlist(["Sun", "Sea", "Sky"]). The songs go into a private field; no client can readsongs. - 2
Ask for an iterator
The client calls
list.iterator(). The playlist createsit, aPlaylistIteratorwith a reference to the same array (not a copy) andindex = 0, and returns it typed asIterator<string>. - 3
Give it to a client
new Player(list.iterator()): the player holds only the iterator. It has no reference to the playlist at all. - 4
hasNext, then next
player.playNext()callsit.hasNext()(true), thenit.next(), which returns"Sun"and moves the cursor:it.indexbecomes 1. - 5
A second, independent iterator
preview.show(list)callslist.iterator()again and getsit2, starting atindex = 0. In the Objects viewitstill showsindex = 1. - 6
The loop
The preview repeats
it2.hasNext()andit2.next():"Sun","Sea","Sky", withit2.indexclimbing to 3. The fourthhasNext()returnsfalseand the loop ends with"Sun, Sea, Sky". - 7
Store in pages (change request)
With the change applied, the playlist stores pages and the iterator's cursor becomes
pageandpos. On the secondnext()ofit2the page is used up, so one step showspage = 1, pos = 0.Player,Previewand the client code are byte-for-byte the same, and print the same result.
Before and after
Without the pattern
- The storage (
songs) is public, and every client indexes it - Each client keeps its own cursor and its own bounds check
- Changing the storage edits the collection and every client loop
- Any client can also modify the collection's internals
- No extra classes; fine for a private array used in one place
With Iterator
- The storage is private; clients see only
hasNext()andnext() - The cursor lives in the iterator, one per traversal
- Changing the storage edits the collection and its iterator only
- Several traversals can run at once, at different positions
- Works with the language's loops when you implement its protocol
| Change request: store in pages | Before | With Iterator |
|---|---|---|
| Existing classes edited | 3 (Playlist, Player, Preview) | 2 (Playlist, PlaylistIterator) |
| Client classes edited | 2 | 0 |
| New classes | 0 | 0 |
| Lines changed in existing classes | 32 (+23 −9) | 32 (+22 −10) |
Look closely at the lines: they come out equal. Writing a paged cursor costs the same code whether it lives in an iterator or in a client. The difference is where it lands. Before, 22 of the 32 lines are in clients (16 in Player, 6 in Preview), and every further client that loops over the playlist (shuffle, search, export) adds its own copy. With Iterator, all 32 lines are in the collection and its iterator, the two classes that are supposed to know the storage, and the count stays 32 however many clients exist.
Variations
External and internal iterators
The visualizer shows an external iterator: the client drives the loop by calling hasNext() and next(). An internal iterator turns this around: the collection runs the loop and calls a function you pass for each element, as in list.forEach(song => play(song)).
External (hasNext/next, for...of) | Internal (forEach, callbacks) | |
|---|---|---|
| Who drives the loop | The client | The collection |
| Stop early | Just break or return | Awkward: Array.prototype.forEach cannot break; use some, find or an exception |
| Walk two collections in step | Easy: two iterators, one loop (merging sorted lists, comparing trees) | Hard: each collection wants to own the loop |
| Pause and resume later | Keep the iterator; continue tomorrow | Not possible; the call runs to the end |
| Writing the traversal | Harder: the state must be saved between calls (generators fix this) | Easy: an ordinary loop or recursion |
| Examples | Java Iterator, Python next(), C++ ++it | JavaScript forEach, Java Iterable.forEach, Ruby each with a block |
Iteration protocols built into languages
Every mainstream language standardizes the Iterator interface so that its loops, spread syntax and library functions accept any collection that implements it. Implement the protocol once and your collection works everywhere.
| Language | Iterable (the factory method) | Iterator | End of sequence | Loop |
|---|---|---|---|---|
| JavaScript / TypeScript | [Symbol.iterator]() | next() returning { value, done } | done: true | for...of, spread [...x], destructuring, Array.from |
| Python | __iter__() | __next__(); next(it, default) | raise StopIteration | for x in, list(), sum(), comprehensions |
| Java | Iterable<T>.iterator() | Iterator<T>: hasNext(), next(), optional remove() | hasNext() is false; next() throws NoSuchElementException | for-each: for (T x : items) |
| C++ | begin() and end() | An iterator type with *it and ++it | it == end() (a half-open range) | range-based for (auto& x : c), algorithms on iterator pairs, C++20 ranges |
| C# | IEnumerable<T>.GetEnumerator() | IEnumerator<T>: MoveNext(), Current | MoveNext() returns false | foreach, LINQ |
class Playlist {
private songs = ["Sun", "Sea", "Sky"];
// By hand: return an object with next() -> { value, done }.
[Symbol.iterator](): Iterator<string> {
let i = 0;
const songs = this.songs;
return {
next: () =>
i < songs.length
? { value: songs[i++], done: false }
: { value: undefined, done: true },
};
}
}
// A generator writes the same iterator as a plain loop: each
// yield pauses the function, and its local variables are the cursor.
function* reversed(songs: string[]): Generator<string> {
for (let i = songs.length - 1; i >= 0; i--) yield songs[i];
}
for (const s of new Playlist()) console.log(s); // Sun Sea Sky
console.log([...reversed(["Sun", "Sea", "Sky"])]); // Sky Sea Sunclass Countdown:
def __init__(self, start: int) -> None:
self.n = start
def __iter__(self) -> "Countdown":
return self # an iterator is its own iterable
def __next__(self) -> int:
if self.n <= 0:
raise StopIteration
self.n -= 1
return self.n + 1
def countdown(start: int): # the same thing as a generator
while start > 0:
yield start
start -= 1
print(list(Countdown(3))) # [3, 2, 1]
print(list(countdown(3))) # [3, 2, 1]Generators (function* and yield in JavaScript, yield in Python, yield return in C#) are the most common way to write an iterator today. The compiler turns the function into an iterator object whose cursor is the paused function itself: its local variables and the line it stopped at. Writing a stack-based tree walk as a generator is a few lines; as a hand-written class it needs the explicit stack you see in the second implementation below.
Lazy and infinite sequences
An iterator computes the next element only when asked, so the sequence does not have to exist in memory, or even be finite. Reading a 50 GB log file line by line, streaming rows from a database, or generating all natural numbers all work the same way, as long as the consumer stops: itertools.count() with itertools.islice in Python, Stream.iterate(1, n -> n + 1).limit(10) in Java, std::views::iota(1) | std::views::take(10) in C++20, or a while (true) yield n++ generator in JavaScript. Pipelines of lazy steps (map, filter, take) process one element at a time end to end, which is also how Java streams and C++ ranges avoid building intermediate lists.
Traversal orders and tree iterators
One collection can offer several iterators: forward and reverse (rbegin() in C++, reversed() in Python, ListIterator.previous() in Java), or in-order, pre-order and level-order for a tree (see Tree Traversals). A tree iterator cannot keep a single index: it keeps a stack of the nodes still to visit (a queue for level-order). That stack is exactly what recursion keeps on the call stack, moved into an object so the walk can pause after each element. This is how you walk a Composite structure without recursion, and the same idea works over a Linked Lists node chain, where the cursor is a pointer to the current node.
Changing the collection while iterating
- Java, fail-fast iterators.
ArrayList,HashMapand mostjava.utilcollections count structural changes in amodCountfield. Their iterators remember the count and throwConcurrentModificationExceptionon the next call if it changed, for example when a for-each loop callslist.remove(x). The check is best effort, not a guarantee. Remove through the iterator (it.remove()) or uselist.removeIf(...). Concurrent collections behave differently:CopyOnWriteArrayListiterates over a snapshot, andConcurrentHashMapiterators are weakly consistent and never throw. - C++, iterator invalidation. C++ does not check; it is undefined behavior. A
std::vectorthat reallocates onpush_backinvalidates every iterator, pointer and reference into it, anderaseinvalidates iterators at and after the erased element. The idiom isit = v.erase(it);(erase returns the next valid iterator), orstd::erase_ifin C++20. Node-based containers such asstd::listandstd::maponly invalidate iterators to the erased element. - Python. Changing a dict's size during iteration raises
RuntimeError: dictionary changed size during iteration. Removing from a list while looping over it raises nothing but silently skips elements. Iterate over a copy (for x in list(items)) or build a new list. - Robust iterators. Some designs promise that iteration survives changes (GoF calls these robust iterators): snapshot iteration, or a collection that notifies its live iterators. They cost memory or bookkeeping, so most libraries choose fail-fast or "undefined" instead.
Cursors and pagination: Iterator at system scale
An API that returns a large list in pages applies the same idea across a network. The server hands the client an opaque cursor (next_cursor, Stripe's starting_after with has_more), the client asks for the next page with it, and the server is free to change how and where the rows are stored because clients never see offsets into its tables. Cursor pagination also tolerates inserts better than ?offset=40, which skips or repeats rows when data changes between requests. Database cursors (JDBC's ResultSet.next()), MongoDB's find() cursor and Redis's SCAN command (call it with the returned cursor until it returns 0) are the same shape. See API Design: REST, GraphQL & gRPC for cursor versus offset pagination.
More variations
| Variation | Idea | Example |
|---|---|---|
| Null iterator | An iterator over nothing, so a leaf can answer "my children" without a null check | Collections.emptyIterator() in Java; iter(()) in Python |
| Peeking iterator | Adds peek() to look at the next element without consuming it | Guava's PeekingIterator; parsers that need one token of lookahead |
| Filtering or mapping iterator | Wraps another iterator and skips or transforms elements: a Decorator for iterators | Python's filter and map, Java streams, C++ views::filter |
| Bidirectional and random access | The cursor can move backward or jump | Java ListIterator; C++ iterator categories (input, forward, bidirectional, random access, contiguous) |
| Async iterator | next() returns a promise, for data that arrives over time | for await...of over Symbol.asyncIterator in JavaScript; async for in Python |
In real code
| Where | Collection | Iterator |
|---|---|---|
| Java collections | Every Collection implements Iterable | ArrayList and HashMap return private inner iterator classes; for-each compiles to iterator(), hasNext(), next() |
| Java I/O | Scanner, DirectoryStream<Path> | Scanner implements Iterator<String>; a directory stream is iterated with for-each |
| Python | Lists, dicts, sets, files, range, os.scandir() | for line in open(path) reads lines lazily; dict.items() returns a view you iterate |
| JavaScript | Array, Map, Set, String, NodeList | map.entries() and str.matchAll(re) return iterators; Node.js readable streams are async iterable |
| C++ standard library | Every container | std::find(v.begin(), v.end(), x): one algorithm, any container, through iterators |
| Go | Since Go 1.23, functions of type iter.Seq | for x := range seq works with user-defined iterators |
| Databases and APIs | Query results, list endpoints | JDBC ResultSet.next(), Redis SCAN, cursor-based pagination in REST APIs |
When to use it, and when not to
Reach for Iterator when
- The collection's storage may change, or is not a plain array (tree, pages, graph, file, network)
- Clients need several traversal orders, or several traversals at once
- Elements should be produced lazily, or the sequence is unbounded
- You want your collection to work with
forloops and the standard library - You want to hide the storage so clients cannot modify it
Skip a custom iterator when
- A built-in collection already does it: just return it or expose a read-only view
- A generator function gives the same result in five lines
- Clients need random access by index or the size; a
get(i)andsize()API is clearer - There is one private array used by one class
Iterator vs similar patterns
| Pattern | What it does | How it relates to Iterator |
|---|---|---|
| Iterator | Walks a collection one element at a time; the cursor lives in the iterator | The pattern itself |
| Composite | Builds a tree in which parts and wholes share one interface | A composite is a common thing to iterate. An iterator with a stack walks it without recursion and without the client knowing the tree's shape |
| Visitor | Adds an operation over a structure of different element types, by double dispatch | Iterator walks, Visitor acts. They combine: iterate the elements and call element.accept(visitor) on each |
| Factory Method | Lets a class decide which concrete class to create | iterator() is a factory method: each collection creates its own concrete iterator behind the shared interface |
| Memento | Captures an object's state so it can be restored later | An iterator's position is state: a saved cursor (a page token, a resume point) is a memento of the iteration. GoF notes iterators can use mementos internally |
| Observer | The subject pushes each new value to subscribers | The opposite direction: Iterator is pull (the consumer asks for the next value), Observer is push. Reactive streams combine both ideas |
Implementation
The visualizer's After version with the change request applied: the playlist stores its songs in pages of two, and only Playlist and its iterator know it. Player keeps one iterator and plays song by song; Preview walks the whole playlist with its own iterator. Each language also plugs into its native iteration protocol: Symbol.iterator in TypeScript, Iterable in Java, __iter__ and __next__ in Python.
from collections.abc import Iterator
class PlaylistIterator:
"""Cursor over a playlist's pages, using Python's protocol."""
def __init__(self, pages: list[list[str]]) -> None:
self._pages = pages
self._page = 0
self._pos = 0
def __iter__(self) -> "PlaylistIterator":
return self # an iterator is also iterable
def __next__(self) -> str:
if self._page >= len(self._pages):
raise StopIteration # Python's "no next element"
p = self._pages[self._page]
song = p[self._pos]
self._pos += 1
if self._pos == len(p):
self._page += 1
self._pos = 0
return song
class Playlist:
def __init__(self, songs: list[str]) -> None:
# Internal storage: pages of up to 2 songs.
self._pages = [songs[i:i + 2] for i in range(0, len(songs), 2)]
def __iter__(self) -> PlaylistIterator:
# Factory method, called by for loops, list(), iter() ...
return PlaylistIterator(self._pages)
class Player:
def __init__(self, it: Iterator[str]) -> None:
self._it = it
def play_next(self) -> str:
return next(self._it, "") # "" once the iterator is used up
class Preview:
def show(self, playlist: Playlist) -> str:
return ", ".join(song for song in playlist)
if __name__ == "__main__":
playlist = Playlist(["Sun", "Sea", "Sky"])
player = Player(iter(playlist))
print(player.play_next()) # Sun
print(Preview().show(playlist)) # Sun, Sea, Sky
print(player.play_next()) # SeaKey takeaways
- Iterator gives sequential access to a collection's elements without exposing how they are stored; clients see only
hasNext()andnext()(or the language's equivalent). - The cursor lives in the iterator, not the collection, so every call to
iterator()starts an independent traversal: in the visualizeritstays at index 1 whileit2walks to the end. iterator()is a factory method: each collection creates its own concrete iterator behind one interface.- Changing the storage to pages edited 2 classes (the playlist and its iterator) instead of 3, and 0 clients instead of 2. The line totals were equal (32 each); what changed is that no client was touched.
- Modern languages build the pattern in (
Symbol.iterator,__iter__/__next__,Iterable,begin()/end()), and generators are the easiest way to write one, including lazy and infinite sequences. - Do not change a collection while iterating it unless the iterator allows it: Java fails fast with
ConcurrentModificationException, C++ gives undefined behavior.
Common pitfalls
- Modifying the collection inside a loop over it (
list.remove(x)in a Java for-each,push_backon astd::vectoryou are iterating). Remove through the iterator, collect changes and apply them after, or useremoveIf/erase_if. - Consuming a single-use iterator or generator twice and getting nothing the second time. Keep the iterable and ask it for a new iterator.
- Calling
next()without checkinghasNext(), or writing ahasNext()that changes state.hasNext()must be safe to call any number of times. - Exposing the internal collection anyway (a getter returning the mutable list) next to the iterator, so clients go back to indexing it.
- Keeping an iterator or C++ iterator after its collection is destroyed or reallocated: a dangling reference that crashes or reads garbage.
Interview tips
- Define it in one sentence, then stress the two benefits: the storage stays private (and can change), and the cursor lives in the iterator (so traversals are independent). Mention that
iterator()is a factory method. - Expect "implement a BST iterator" (LeetCode 173) or "flatten a nested list iterator": keep an explicit stack, make
hasNext()side-effect free, and state the complexity: amortized O(1) pernext(), O(h) memory. - Know your language's protocol and its failure mode:
StopIterationin Python,{ done: true }in JavaScript,NoSuchElementExceptionandConcurrentModificationExceptionin Java, iterator invalidation in C++. - Connect it to system design: cursor-based pagination and database cursors are iterators across a network, and they beat offset pagination when data changes between pages.
Real-world applications
- Every collection library: lists, maps, sets, trees, graphs.
- Streaming large data: reading files line by line, database result sets, log processing.
- Cursor-based pagination in REST and GraphQL APIs, and
SCANin Redis. - Tree and graph walks (DOM traversal with
TreeWalker, file system walks withos.walk). - Lazy pipelines: Java streams, C++ ranges, Python generators and
itertools. - Parsers and tokenizers that hand out one token at a time, often with a peek.
Practice problems
Test yourself
In the visualizer, the player has played one song when the preview lists the playlist. Why does it.index stay at 1 while it2.index climbs to 3?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.