Patterncore
Iterator pattern
Also called Iterator, Cursor, enumerator.
An iterator object gives the elements of a collection one at a time and keeps the position, so a client can walk any collection without knowing how it stores them.
- Family
- behavioral-design
- Intent
- Give sequential access to the elements of an aggregate object without exposing how the aggregate stores them.
- Also called
- Cursor
Intent
Give sequential access to the elements of an aggregate object, such as a list or a tree, without exposing how the aggregate stores them.1 The object that walks the aggregate is the iterator. It holds the position of one traversal, so the aggregate does not have to.
This page is about the design pattern: the roles, the choices and the trade-offs. The language rules of each iteration protocol (the loop statements, the end signal, the pitfalls of each language) are on Iterator.
Problem
A binary search tree stores its keys in nodes with left and right children. A client wants the keys in ascending order. It does not want to know about nodes, and the tree does not want to expose them, because then it could never change its layout.
The first design puts the traversal in the tree: a method in_order() that returns a list. This copies every key before the client sees the first one, and a client that needs only the smallest key pays for all of them. The second design gives the tree a cursor: first(), next(), done(). Now the tree holds the position, so only one traversal can run at a time. A client that compares two positions in the same tree, or a loop inside a loop, breaks.
The forces are these. The client must not depend on the representation of the aggregate. The aggregate must support more than one way to traverse it (in order, by level, in reverse) without a method for each in its own interface. More than one traversal must be able to run at the same time.1 And one loop statement, one sum and one take should work for every kind of collection.
Solution
Move the position out of the aggregate into a separate object. Design Patterns names four participants.1
- Iterator defines the interface to get the elements one at a time.
- ConcreteIterator implements that interface for one aggregate and one order of traversal. It keeps track of the current position.
- Aggregate defines an operation that makes an iterator.
- ConcreteAggregate implements that operation and returns a ConcreteIterator.
Client
| for key in tree
v
Aggregate (Tree) Iterator (protocol)
------------------------ --------------------
root (private) next(): element or end
make_iterator() ----- creates ----> ^
|
InOrderIterator
stack of nodes that are left
The operation that makes the iterator is a factory method: the aggregate decides which iterator class the client gets.1 See Factory Method pattern. Because each call makes another iterator with its own state, two traversals of the same tree are two objects and do not disturb each other.
Python shows the classic form. Tree.__iter__ is the factory method, and InOrderIterator keeps a stack of the nodes whose keys it has not yet given. Python asks an iterator for __next__, which raises StopIteration at the end, and for an __iter__ that returns the iterator itself.2
class Node:
def __init__(self, key, left=None, right=None):
self.key, self.left, self.right = key, left, right
class InOrderIterator:
def __init__(self, root):
self._stack = []
self._push_left(root)
def _push_left(self, node):
while node is not None:
self._stack.append(node)
node = node.left
def __iter__(self):
return self
def __next__(self):
if not self._stack:
raise StopIteration
node = self._stack.pop()
self._push_left(node.right)
return node.key
class Tree:
def __init__(self, root):
self._root = root
def __iter__(self): # the factory method
return InOrderIterator(self._root)
tree = Tree(Node(5, Node(3, Node(1), Node(4)), Node(8, None, Node(9))))
print(list(tree))
print([(x, y) for x in tree for y in tree if x + y == 9])
[1, 3, 4, 5, 8, 9]
[(1, 8), (4, 5), (5, 4), (8, 1)]
The nested comprehension runs two traversals of one tree at the same time. Each for asks the tree for its own iterator.
Generators write the iterator for you
The iterator class above stores its position by hand, in a stack. A generator stores it in a suspended function call. The body runs up to yield, gives a value, and resumes from that point on the next request. PEP 255 gives this as the reason for generators: a producer that must keep state between values otherwise needs a callback or a hand-written state object.34 The same tree with a generator needs no iterator class:
class Node:
def __init__(self, key, left=None, right=None):
self.key, self.left, self.right = key, left, right
class Tree:
def __init__(self, root):
self._root = root
def __iter__(self):
def walk(node):
if node is not None:
yield from walk(node.left)
yield node.key
yield from walk(node.right)
return walk(self._root)
tree = Tree(Node(5, Node(3, Node(1), Node(4)), Node(8, None, Node(9))))
print(list(tree))
[1, 3, 4, 5, 8, 9]
JavaScript generator functions, C# iterator methods with yield return, and the C++ coroutine type std::generator do the same.61113 In C#, the compiler turns the method body into an enumerator class, and the body does not start until the caller asks for the first element.11 The pattern did not go away. The compiler writes the ConcreteIterator.
External and internal iteration
Design Patterns asks who controls the iteration.1 With an external iterator, the client asks for each element: next() in Python, JavaScript and Rust, hasNext() and next() in Java, MoveNext() in C#, ++it in C++. With an internal iterator, the client passes an operation, and the iterator applies it to each element: Iterable.forEach in Java, for_each in Rust.710
Go makes the internal form the main protocol. A function of type func(yield func(T) bool) is a range expression, and the body of the for loop becomes the yield function.8 The iterator then keeps its state on its own call stack, so a recursive walk of a tree needs no explicit stack, as the Go example shows. A break in the loop makes yield return false, and the iterator must stop.
An internal iterator is shorter to write. An external iterator is more flexible. Design Patterns gives the comparison of two collections for equality as a task that external iterators make straightforward and internal iterators make very hard.1 The examples compare two trees with the same keys and different shapes. Each one needs two traversals that move in step. Go solves this with iter.Pull, which turns a push iterator into a next function and a stop function.9 CLU had iterators that worked like Go's push form, and the history of CLU records that they could not step through two collections at once.16
Example
Each example file builds a binary search tree from the keys 5, 3, 8, 1, 4, 9 and iterates it in order. It sums the keys, takes the first two, and compares the tree with a tree that has the same keys and another shape, and with a tree that lacks the 9. Each language uses its own protocol, so the tree works with the loop statement and the library functions of the language.
| Language | Protocol | How the example writes the iterator |
|---|---|---|
| Python | __iter__, __next__, StopIteration2 |
a generator method with an explicit stack |
| JavaScript | [Symbol.iterator](), next() returns { value, done }5 |
a generator method; the iterator helpers take and reduce |
| TypeScript | as JavaScript, typed as Iterable<T> and Iterator<T> |
a hand-written iterator class |
| Java | Iterable<T>, Iterator<T>7 |
an anonymous class with a stack |
| C# | IEnumerable<T>, IEnumerator<T> |
an iterator method with yield return; LINQ |
| Go | iter.Seq[T], range over a function8 |
a recursive push iterator; iter.Pull for the comparison |
| Rust | the trait Iterator, IntoIterator10 |
a struct that borrows the nodes; Iterator::eq |
| C++ | a range: begin() and end()12 |
a forward iterator class checked by static_assert |
| C | none | a struct with a stack and a next function |
from collections.abc import Iterator
from itertools import islice, zip_longest
class Node:
def __init__(self, key: int) -> None:
self.key = key
self.left: Node | None = None
self.right: Node | None = None
class Tree:
"""A binary search tree. Iteration gives the keys in ascending order."""
def __init__(self, *keys: int) -> None:
self._root: Node | None = None
for key in keys:
self.insert(key)
def insert(self, key: int) -> None:
if self._root is None:
self._root = Node(key)
return
node = self._root
while True:
if key < node.key:
if node.left is None:
node.left = Node(key)
return
node = node.left
else:
if node.right is None:
node.right = Node(key)
return
node = node.right
def __iter__(self) -> Iterator[int]:
# A generator: each call makes a fresh iterator with its own stack.
stack: list[Node] = []
node = self._root
while stack or node is not None:
while node is not None:
stack.append(node)
node = node.left
node = stack.pop()
yield node.key
node = node.right
def same_keys(a: Tree, b: Tree) -> bool:
missing = object()
return all(x == y for x, y in zip_longest(a, b, fillvalue=missing))
a = Tree(5, 3, 8, 1, 4, 9)
b = Tree(1, 3, 4, 5, 8, 9) # the same keys, a different shape
c = Tree(1, 3, 4, 5, 8)
print("in order:", *a)
print("sum:", sum(a))
print("first two:", *islice(a, 2))
print("same keys as b:", "yes" if same_keys(a, b) else "no")
print("same keys as c:", "yes" if same_keys(a, c) else "no")
in order: 1 3 4 5 8 9
sum: 30
first two: 1 3
same keys as b: yes
same keys as c: no
- Verdict: native. A class is iterable when
__iter__returns an iterator, and an iterator has__next__. A generator function returns an object that has both. __iter__is a generator, so eachforloop,sumandislicecall gets a fresh iterator with its own stack. Two traversals of the same tree can run at once, aszip_longest(a, b)shows.zip_longestwith a sentinelfillvaluemakes trees of different sizes compare unequal. Plainzipstops at the shorter tree.- The explicit stack keeps the depth of the Python call stack constant. A recursive generator with
yield fromis shorter, but it nests one generator frame for each level of the tree.
#include <algorithm>
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <memory>
#include <ranges>
#include <vector>
class Tree {
struct Node {
int key;
std::unique_ptr<Node> left, right;
};
std::unique_ptr<Node> root_;
public:
// A forward iterator: a copy is an independent position in the same tree.
class iterator {
std::vector<const Node*> stack_;
void push_left(const Node* node) {
for (; node != nullptr; node = node->left.get()) {
stack_.push_back(node);
}
}
public:
using value_type = int;
using difference_type = std::ptrdiff_t;
using iterator_concept = std::forward_iterator_tag;
iterator() = default;
explicit iterator(const Node* root) { push_left(root); }
int operator*() const { return stack_.back()->key; }
iterator& operator++() {
const Node* node = stack_.back();
stack_.pop_back();
push_left(node->right.get());
return *this;
}
iterator operator++(int) {
iterator old = *this;
++*this;
return old;
}
bool operator==(const iterator&) const = default;
};
Tree(std::initializer_list<int> keys) {
for (int key : keys) {
insert(key);
}
}
void insert(int key) {
std::unique_ptr<Node>* link = &root_;
while (*link) {
link = key < (*link)->key ? &(*link)->left : &(*link)->right;
}
*link = std::make_unique<Node>(Node{key, nullptr, nullptr});
}
iterator begin() const { return iterator(root_.get()); }
iterator end() const { return iterator(); }
};
static_assert(std::forward_iterator<Tree::iterator>);
static_assert(std::ranges::forward_range<Tree>);
int main() {
const Tree a{5, 3, 8, 1, 4, 9};
const Tree b{1, 3, 4, 5, 8, 9};
const Tree c{1, 3, 4, 5, 8};
std::cout << "in order:";
int sum = 0;
for (int key : a) {
std::cout << ' ' << key;
sum += key;
}
std::cout << "\nsum: " << sum << "\nfirst two:";
for (int key : a | std::views::take(2)) {
std::cout << ' ' << key;
}
std::cout << "\nsame keys as b: " << (std::ranges::equal(a, b) ? "yes" : "no")
<< "\nsame keys as c: " << (std::ranges::equal(a, c) ? "yes" : "no") << '\n';
}
in order: 1 3 4 5 8 9
sum: 30
first two: 1 3
same keys as b: yes
same keys as c: no
- Verdict: native. A type with
begin()andend()is a range. The range-basedforstatement and thestd::rangesalgorithms work on it. - The iterator holds the stack of nodes that are left. The end iterator has an empty stack, so the defaulted
operator==compares the stacks and finds the end. - The
static_assertlines ask the compiler to check the iterator against the C++20 concepts. A missingdifference_typeor a wrong return type fails here, not deep inside an algorithm. std::views::take(2)is lazy, andstd::ranges::equalstops at the first difference. C++23 addsstd::generator, a coroutine type that is a range, which would letbeginbe written withco_yield.
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.StringJoiner;
import java.util.stream.StreamSupport;
public class Main {
static final class Tree implements Iterable<Integer> {
private static final class Node {
final int key;
Node left;
Node right;
Node(int key) {
this.key = key;
}
}
private Node root;
Tree(int... keys) {
for (int key : keys) {
insert(key);
}
}
void insert(int key) {
if (root == null) {
root = new Node(key);
return;
}
Node node = root;
while (true) {
if (key < node.key) {
if (node.left == null) {
node.left = new Node(key);
return;
}
node = node.left;
} else {
if (node.right == null) {
node.right = new Node(key);
return;
}
node = node.right;
}
}
}
// The factory method of the aggregate: a fresh iterator for each traversal.
@Override
public Iterator<Integer> iterator() {
return new Iterator<>() {
private final Deque<Node> stack = new ArrayDeque<>();
{
pushLeft(root);
}
private void pushLeft(Node node) {
for (; node != null; node = node.left) {
stack.push(node);
}
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public Integer next() {
if (stack.isEmpty()) {
throw new NoSuchElementException();
}
Node node = stack.pop();
pushLeft(node.right);
return node.key;
}
};
}
}
static boolean sameKeys(Iterable<Integer> a, Iterable<Integer> b) {
Iterator<Integer> left = a.iterator();
Iterator<Integer> right = b.iterator();
while (left.hasNext() && right.hasNext()) {
if (!left.next().equals(right.next())) {
return false;
}
}
return !left.hasNext() && !right.hasNext();
}
public static void main(String[] args) {
Tree a = new Tree(5, 3, 8, 1, 4, 9);
Tree b = new Tree(1, 3, 4, 5, 8, 9);
Tree c = new Tree(1, 3, 4, 5, 8);
StringJoiner keys = new StringJoiner(" ");
for (int key : a) {
keys.add(Integer.toString(key));
}
System.out.println("in order: " + keys);
int sum = StreamSupport.stream(a.spliterator(), false).mapToInt(Integer::intValue).sum();
System.out.println("sum: " + sum);
Iterator<Integer> it = a.iterator();
System.out.println("first two: " + it.next() + " " + it.next());
System.out.println("same keys as b: " + (sameKeys(a, b) ? "yes" : "no"));
System.out.println("same keys as c: " + (sameKeys(a, c) ? "yes" : "no"));
}
}
in order: 1 3 4 5 8 9
sum: 30
first two: 1 3
same keys as b: yes
same keys as c: no
- Verdict: native. A class that implements
Iterable<T>can be the target of the enhancedforstatement. Itsiterator()method returns anIterator<T>withhasNext()andnext(). iterator()is a factory method. Each call makes an anonymous class with its own stack, sosameKeysruns two traversals at once.- Java has no generators, so the state of the traversal lives in fields of the iterator.
next()throwsNoSuchElementExceptionat the end, as theIteratorcontract asks. Iterablehas a defaultspliterator(), soStreamSupport.streamturns the tree into a stream.Iterable.forEachis the internal form: the tree calls the action for each element.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
struct node *left, *right;
};
static struct node *insert(struct node *root, int key) {
struct node **link = &root;
while (*link != NULL) {
link = key < (*link)->key ? &(*link)->left : &(*link)->right;
}
*link = calloc(1, sizeof **link);
if (*link == NULL) {
exit(1);
}
(*link)->key = key;
return root;
}
static void destroy(struct node *n) {
if (n != NULL) {
destroy(n->left);
destroy(n->right);
free(n);
}
}
/* The iterator: the stack of nodes that are left. 64 levels is enough for this example. */
struct tree_iter {
const struct node *stack[64];
int top;
};
static void push_left(struct tree_iter *it, const struct node *n) {
for (; n != NULL; n = n->left) {
it->stack[it->top++] = n;
}
}
static void tree_iter_init(struct tree_iter *it, const struct node *root) {
it->top = 0;
push_left(it, root);
}
/* Writes the next key to *key and returns true, or returns false at the end. */
static bool tree_iter_next(struct tree_iter *it, int *key) {
if (it->top == 0) {
return false;
}
const struct node *n = it->stack[--it->top];
push_left(it, n->right);
*key = n->key;
return true;
}
static bool same_keys(const struct node *a, const struct node *b) {
struct tree_iter left, right;
tree_iter_init(&left, a);
tree_iter_init(&right, b);
int x, y;
for (;;) {
bool has_x = tree_iter_next(&left, &x);
bool has_y = tree_iter_next(&right, &y);
if (!has_x || !has_y) {
return has_x == has_y;
}
if (x != y) {
return false;
}
}
}
static struct node *from_keys(const int *keys, int count) {
struct node *root = NULL;
for (int i = 0; i < count; i++) {
root = insert(root, keys[i]);
}
return root;
}
int main(void) {
const int ka[] = {5, 3, 8, 1, 4, 9}, kb[] = {1, 3, 4, 5, 8, 9}, kc[] = {1, 3, 4, 5, 8};
struct node *a = from_keys(ka, 6), *b = from_keys(kb, 6), *c = from_keys(kc, 5);
struct tree_iter it;
int key, sum = 0;
printf("in order:");
for (tree_iter_init(&it, a); tree_iter_next(&it, &key);) {
printf(" %d", key);
sum += key;
}
printf("\nsum: %d\nfirst two:", sum);
tree_iter_init(&it, a);
for (int i = 0; i < 2 && tree_iter_next(&it, &key); i++) {
printf(" %d", key);
}
printf("\nsame keys as b: %s\n", same_keys(a, b) ? "yes" : "no");
printf("same keys as c: %s\n", same_keys(a, c) ? "yes" : "no");
destroy(a);
destroy(b);
destroy(c);
return 0;
}
in order: 1 3 4 5 8 9
sum: 30
first two: 1 3
same keys as b: yes
same keys as c: no
- Verdict: idiom. C has no iterator protocol and no loop statement that calls one. A struct that holds the position and a
nextfunction that returnsfalseat the end is the usual form. - The caller owns the iterator struct, here on the stack. Two iterators over the same tree are two structs, so
same_keysruns two traversals at once. - Nothing ties the iterator to the tree. If the program frees or changes the tree while an iterator holds node pointers, the next call reads freed memory, and the compiler does not warn.
- The fixed array of 64 entries limits the depth of the tree. A real program grows the stack with
realloc, or stores parent pointers in the nodes and needs no stack.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
var a = new Tree(5, 3, 8, 1, 4, 9);
var b = new Tree(1, 3, 4, 5, 8, 9);
var c = new Tree(1, 3, 4, 5, 8);
Console.WriteLine($"in order: {string.Join(" ", a)}");
Console.WriteLine($"sum: {a.Sum()}");
Console.WriteLine($"first two: {string.Join(" ", a.Take(2))}");
Console.WriteLine($"same keys as b: {(a.SequenceEqual(b) ? "yes" : "no")}");
Console.WriteLine($"same keys as c: {(a.SequenceEqual(c) ? "yes" : "no")}");
sealed class Tree : IEnumerable<int>
{
sealed class Node(int key)
{
public int Key { get; } = key;
public Node? Left { get; set; }
public Node? Right { get; set; }
}
Node? root;
public Tree(params int[] keys)
{
foreach (int key in keys)
{
Insert(key);
}
}
public void Insert(int key)
{
if (root is null)
{
root = new Node(key);
return;
}
Node node = root;
while (true)
{
if (key < node.Key)
{
if (node.Left is null) { node.Left = new Node(key); return; }
node = node.Left;
}
else
{
if (node.Right is null) { node.Right = new Node(key); return; }
node = node.Right;
}
}
}
// An iterator method: the compiler turns it into an IEnumerator<int> class.
public IEnumerator<int> GetEnumerator()
{
var stack = new Stack<Node>();
Node? node = root;
while (stack.Count > 0 || node is not null)
{
while (node is not null)
{
stack.Push(node);
node = node.Left;
}
node = stack.Pop();
yield return node.Key;
node = node.Right;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
in order: 1 3 4 5 8 9
sum: 30
first two: 1 3
same keys as b: yes
same keys as c: no
- Verdict: native. A class implements
IEnumerable<T>with aGetEnumeratormethod, andforeachdrives theIEnumerator<T>throughMoveNextandCurrent. GetEnumeratoris an iterator method. The compiler turns the body withyield returninto a state machine class, and each call starts a fresh traversal.- LINQ works on any
IEnumerable<T>.Take(2)stops the enumerator after two keys, andSequenceEqualsteps two enumerators together. - The non-generic
IEnumerable.GetEnumeratoris still required, becauseIEnumerable<T>extends the olderIEnumerable.
class Tree {
#root = null;
constructor(...keys) {
for (const key of keys) this.insert(key);
}
insert(key) {
const leaf = { key, left: null, right: null };
if (this.#root === null) {
this.#root = leaf;
return;
}
let node = this.#root;
for (;;) {
const side = key < node.key ? "left" : "right";
if (node[side] === null) {
node[side] = leaf;
return;
}
node = node[side];
}
}
// A generator method: each call makes a fresh iterator.
*[Symbol.iterator]() {
const stack = [];
let node = this.#root;
while (stack.length > 0 || node !== null) {
while (node !== null) {
stack.push(node);
node = node.left;
}
node = stack.pop();
yield node.key;
node = node.right;
}
}
}
// External iteration: the caller drives two iterators side by side.
function sameKeys(a, b) {
const left = a[Symbol.iterator]();
const right = b[Symbol.iterator]();
for (;;) {
const x = left.next();
const y = right.next();
if (x.done || y.done) return x.done && y.done;
if (x.value !== y.value) return false;
}
}
const a = new Tree(5, 3, 8, 1, 4, 9);
const b = new Tree(1, 3, 4, 5, 8, 9);
const c = new Tree(1, 3, 4, 5, 8);
console.log("in order:", ...a);
console.log("sum:", a[Symbol.iterator]().reduce((total, key) => total + key, 0));
console.log("first two:", ...a[Symbol.iterator]().take(2));
console.log("same keys as b:", sameKeys(a, b) ? "yes" : "no");
console.log("same keys as c:", sameKeys(a, c) ? "yes" : "no");
in order: 1 3 4 5 8 9
sum: 30
first two: 1 3
same keys as b: yes
same keys as c: no
- Verdict: native. An object is iterable when it has a method under the key
Symbol.iteratorthat returns an iterator, an object whosenext()returns{ value, done }. - A generator method (
*[Symbol.iterator]()) gives the iterator with no hand-writtennext. The spread...aandfor...ofboth call it. - The generator object inherits from
Iterator.prototype, so the iterator helperstakeandreducework on it. They are lazy:take(2)stops the traversal after two keys. sameKeyscallsnext()itself on two iterators. This is external iteration. A callback-styleforEachcould not compare two trees step by step.
type TreeNode = { key: number; left: TreeNode | null; right: TreeNode | null };
// The concrete iterator of Design Patterns, written by hand.
class InOrderIterator implements Iterator<number> {
#stack: TreeNode[] = [];
constructor(root: TreeNode | null) {
this.#pushLeft(root);
}
#pushLeft(node: TreeNode | null): void {
for (; node !== null; node = node.left) this.#stack.push(node);
}
next(): IteratorResult<number> {
const node = this.#stack.pop();
if (node === undefined) return { done: true, value: undefined };
this.#pushLeft(node.right);
return { done: false, value: node.key };
}
}
// The aggregate. It makes a fresh iterator for each traversal.
class Tree implements Iterable<number> {
#root: TreeNode | null = null;
constructor(...keys: number[]) {
for (const key of keys) this.insert(key);
}
insert(key: number): void {
const leaf: TreeNode = { key, left: null, right: null };
if (this.#root === null) {
this.#root = leaf;
return;
}
let node = this.#root;
for (;;) {
const next: TreeNode | null = key < node.key ? node.left : node.right;
if (next === null) {
if (key < node.key) node.left = leaf;
else node.right = leaf;
return;
}
node = next;
}
}
[Symbol.iterator](): Iterator<number> {
return new InOrderIterator(this.#root);
}
}
function sameKeys(a: Iterable<number>, b: Iterable<number>): boolean {
const left = a[Symbol.iterator]();
const right = b[Symbol.iterator]();
for (;;) {
const x = left.next();
const y = right.next();
if (x.done || y.done) return Boolean(x.done && y.done);
if (x.value !== y.value) return false;
}
}
function* take<T>(source: Iterable<T>, count: number): Generator<T> {
if (count <= 0) return;
for (const item of source) {
yield item;
if (--count === 0) return;
}
}
const a = new Tree(5, 3, 8, 1, 4, 9);
const b = new Tree(1, 3, 4, 5, 8, 9);
const c = new Tree(1, 3, 4, 5, 8);
let sum = 0;
for (const key of a) sum += key;
console.log("in order:", [...a].join(" "));
console.log("sum:", sum);
console.log("first two:", [...take(a, 2)].join(" "));
console.log("same keys as b:", sameKeys(a, b) ? "yes" : "no");
console.log("same keys as c:", sameKeys(a, c) ? "yes" : "no");
in order: 1 3 4 5 8 9
sum: 30
first two: 1 3
same keys as b: yes
same keys as c: no
- Verdict: native, as in JavaScript. The types
Iterable<T>,Iterator<T>andIteratorResult<T>describe the protocol, so the compiler checks the shape ofnext(). InOrderIteratoris the hand-written form: the stack of nodes that are left is the state of one traversal. The generator method of the JavaScript example keeps the same state in a suspended call.takeis a generator over anyIterable<T>. It returns before it asks for a third key, so the iterator of the tree does no more work.- The
#stackand#rootfields are private at run time, so a client cannot reach the nodes through the tree or the iterator.
package main
import (
"fmt"
"iter"
"strings"
)
type node struct {
key int
left, right *node
}
type Tree struct{ root *node }
func NewTree(keys ...int) *Tree {
t := &Tree{}
for _, key := range keys {
t.Insert(key)
}
return t
}
func (t *Tree) Insert(key int) {
link := &t.root
for *link != nil {
if key < (*link).key {
link = &(*link).left
} else {
link = &(*link).right
}
}
*link = &node{key: key}
}
// All is a push iterator: it calls yield for each key, in order.
func (t *Tree) All() iter.Seq[int] {
return func(yield func(int) bool) {
var walk func(n *node) bool
walk = func(n *node) bool {
return n == nil || (walk(n.left) && yield(n.key) && walk(n.right))
}
walk(t.root)
}
}
// SameKeys turns the two push iterators into pull iterators and steps them together.
func SameKeys(a, b *Tree) bool {
nextA, stopA := iter.Pull(a.All())
defer stopA()
nextB, stopB := iter.Pull(b.All())
defer stopB()
for {
x, okA := nextA()
y, okB := nextB()
if !okA || !okB {
return okA == okB
}
if x != y {
return false
}
}
}
func yesNo(ok bool) string {
if ok {
return "yes"
}
return "no"
}
func main() {
a := NewTree(5, 3, 8, 1, 4, 9)
b := NewTree(1, 3, 4, 5, 8, 9)
c := NewTree(1, 3, 4, 5, 8)
var keys []string
sum := 0
for key := range a.All() {
keys = append(keys, fmt.Sprint(key))
sum += key
}
fmt.Println("in order:", strings.Join(keys, " "))
fmt.Println("sum:", sum)
var first []string
for key := range a.All() {
if len(first) == 2 {
break // yield returns false, and walk stops
}
first = append(first, fmt.Sprint(key))
}
fmt.Println("first two:", strings.Join(first, " "))
fmt.Println("same keys as b:", yesNo(SameKeys(a, b)))
fmt.Println("same keys as c:", yesNo(SameKeys(a, c)))
}
in order: 1 3 4 5 8 9
sum: 30
first two: 1 3
same keys as b: yes
same keys as c: no
- Verdict: native. A function of type
iter.Seq[int],func(yield func(int) bool), is a range expression. The loop body becomes theyieldfunction. Allis an internal iterator. The recursivewalkkeeps the traversal state on the call stack, so the code needs no explicit stack.- A
breakin the loop makesyieldreturnfalse. The iterator must then stop and not callyieldagain, which the&&chain inwalkdoes. iter.Pullturns a push iterator into anextfunction and astopfunction.SameKeysneeds it because it must step two trees together. Thedefer stopA()frees the iterator when the comparison ends early.
struct Node {
key: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
#[derive(Default)]
struct Tree {
root: Option<Box<Node>>,
}
impl Tree {
fn from_keys(keys: &[i32]) -> Tree {
let mut tree = Tree::default();
for &key in keys {
tree.insert(key);
}
tree
}
fn insert(&mut self, key: i32) {
let mut link = &mut self.root;
while let Some(node) = link {
link = if key < node.key { &mut node.left } else { &mut node.right };
}
*link = Some(Box::new(Node { key, left: None, right: None }));
}
fn iter(&self) -> Iter<'_> {
let mut it = Iter { stack: Vec::new() };
it.push_left(self.root.as_deref());
it
}
}
/// The iterator borrows the tree, so the tree cannot change while it lives.
struct Iter<'a> {
stack: Vec<&'a Node>,
}
impl<'a> Iter<'a> {
fn push_left(&mut self, mut node: Option<&'a Node>) {
while let Some(n) = node {
self.stack.push(n);
node = n.left.as_deref();
}
}
}
impl<'a> Iterator for Iter<'a> {
type Item = i32;
fn next(&mut self) -> Option<i32> {
let node = self.stack.pop()?;
self.push_left(node.right.as_deref());
Some(node.key)
}
}
impl<'a> IntoIterator for &'a Tree {
type Item = i32;
type IntoIter = Iter<'a>;
fn into_iter(self) -> Iter<'a> {
self.iter()
}
}
fn yes_no(ok: bool) -> &'static str {
if ok { "yes" } else { "no" }
}
fn main() {
let a = Tree::from_keys(&[5, 3, 8, 1, 4, 9]);
let b = Tree::from_keys(&[1, 3, 4, 5, 8, 9]);
let c = Tree::from_keys(&[1, 3, 4, 5, 8]);
let mut keys = Vec::new();
for key in &a {
keys.push(key.to_string());
}
println!("in order: {}", keys.join(" "));
println!("sum: {}", a.iter().sum::<i32>());
let first: Vec<String> = a.iter().take(2).map(|k| k.to_string()).collect();
println!("first two: {}", first.join(" "));
println!("same keys as b: {}", yes_no(a.iter().eq(b.iter())));
println!("same keys as c: {}", yes_no(a.iter().eq(c.iter())));
}
in order: 1 3 4 5 8 9
sum: 30
first two: 1 3
same keys as b: yes
same keys as c: no
- Verdict: native. A type implements the trait
Iteratorwith one required method,next, which returnsOption<Self::Item>. Every adapter (take,map,sum,eq) comes from the trait as a provided method. impl IntoIterator for &Treeletsfor key in &awork. Theforloop callsinto_iteronce and thennextuntilNone.Iter<'a>holds shared borrows of the nodes. The borrow checker rejects a call ofinsertwhile an iterator is alive, so the iterator can never see a tree that changed under it.Iterator::eqcompares two iterators element by element and stops at the first difference. It is the same-fringe comparison in one call.
Consequences
Design Patterns lists three consequences.1
- It supports variations in the traversal. A tree can give an in-order iterator, a level-order iterator and a reverse iterator. Each one is one more class or one more generator. The tree's interface grows by one factory method, not by a traversal algorithm.
- It simplifies the interface of the aggregate. The aggregate does not need
first,nextanddoneof its own. - More than one traversal can be in progress. Each iterator keeps its own state.
A common protocol has one more effect. When every collection gives the same iterator interface, the library can supply the algorithms once: sum, zip, take, filter, SequenceEqual, std::ranges::equal. A lazy chain of adapters computes each element when the consumer asks for it, so a search that stops at the first match does not visit the rest. The JavaScript, C#, Rust and C++ examples use these adapters.
The costs are these.
An iterator can outlive the state it points to. The iterator holds references into the aggregate. If the aggregate changes during a traversal, the iterator may skip elements, give an element twice, or read freed memory. Design Patterns asks for iterators that insertions and removals do not disturb, and it notes that such an iterator must do this without a copy of the aggregate.1 The tree iterator below does not have this property. A key that a traversal inserts behind the current position is missed, and one inserted ahead of it is seen:
This code runs but gives a wrong answer on purpose.
class Node:
def __init__(self, key):
self.key, self.left, self.right = key, None, None
class Tree:
def __init__(self, *keys):
self.root = None
for key in keys:
self.insert(key)
def insert(self, key):
link = self
side = "root"
while getattr(link, side) is not None:
link = getattr(link, side)
side = "left" if key < link.key else "right"
setattr(link, side, Node(key))
def __iter__(self):
stack, node = [], self.root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
yield node.key
node = node.right
tree = Tree(5, 3, 8, 1, 4, 9)
seen = []
for key in tree:
seen.append(key)
if key == 4:
tree.insert(2) # behind the position: missed
tree.insert(6) # ahead of the position: seen
print("seen:", seen)
print("now: ", list(tree))
seen: [1, 3, 4, 5, 6, 8, 9]
now: [1, 2, 3, 4, 5, 6, 8, 9]
There are three usual answers. A fail-fast iterator detects the change and stops with an error: the iterators of java.util.ArrayList compare a modification count on each next() and throw ConcurrentModificationException.14 A snapshot iterator walks a copy, at the cost of the copy. And Rust makes the change impossible: the iterator borrows the tree, so the compiler rejects a call of insert while the iterator is in use. The per-language behaviour, with executed examples, is on Iterator.
An iterator is one pass. Code that keeps an iterator and loops over it twice sees nothing the second time. The aggregate is iterable many times, because it makes a fresh iterator for each loop. The iterator itself is not. A class that returns self from its factory method mixes the two roles, and a nested loop over it breaks:
This code runs but gives a wrong answer on purpose.
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self # the aggregate is its own iterator
def __next__(self):
if self.current == 0:
raise StopIteration
self.current -= 1
return self.current + 1
countdown = Countdown(3)
print([(x, y) for x in countdown for y in countdown])
[(3, 2), (3, 1)]
The inner loop used up the shared position, so the outer loop ended after one element. The fix is to make __iter__ return a fresh iterator (or to make it a generator), as the tree does.
The traversal state is hidden. A debugger shows a suspended generator or an iterator object, not the position in the tree. And an iterator that holds a resource, such as an open file or a database cursor, needs a close step when the loop stops early. JavaScript, for example, calls the optional return method of the iterator to tell it that the caller will not ask for more elements.5
When not to use it
Do not write an iterator class in a language that has generators, unless the iterator needs extra operations (peek, remove, a position that the caller can save). A generator gives the same object with less code and fewer places for the end condition to be wrong.
Do not add an iterator when the collection is already a standard collection. Expose an array, a slice, a list or a read-only view, and the language's own iterator comes with it. A custom iterator over a list that the class could return as a read-only view adds a class and protects nothing more.
Do not use an iterator when the client needs random access. An iterator gives the next element. A client that jumps to index 1000 should get an indexable sequence, a C++ random access iterator, or a direct lookup.
Do not hide expensive work behind next() with no sign. An iterator over a remote API that makes one network call for each element looks like a loop over a list in the client. Batch the calls, or make the cost visible in the name of the operation.
Variants and related patterns
Cursor. Design Patterns describes a variant where the aggregate keeps the traversal algorithm and the iterator stores only the position. It calls this iterator a cursor, because it only points to the current position in the aggregate.1
Null iterator. An iterator that is done at once. Design Patterns uses it for the leaves of a tree, so that code that walks a structure needs no special case for an element with no children.1
Push and pull. An external iterator is pull: the consumer asks. A generator or a Go iterator is push from the inside: the producer runs until it gives a value. Go names its two forms push iterators and pull iterators, and iter.Pull converts one into the other.9 An observer that receives every value of a stream is push with no pause at all. See Observer pattern.
Composite. Iterators are often used on recursive structures such as composites.1 The tree in the examples is a composite of nodes, and its iterator turns the recursive structure into a flat sequence. See Composite pattern.
Visitor. A visitor and an internal iterator both apply an operation to each element. A visitor dispatches on the type of each element and can do something different for each type. An iterator gives elements of one type in an order. See Visitor pattern.
Memento. Design Patterns notes that an iterator can use a memento to capture the state of an iteration, and that the iterator keeps the memento inside itself.1 See Memento pattern.
Factory Method. The operation that makes the iterator is a factory method, and each aggregate returns the iterator class that fits its structure.1 See Factory Method pattern.
Known uses
- OpenJDK: the class
Itrin ArrayList.java at jdk-25+36 is a ConcreteIterator. It keeps a cursor index and the modification count it expects, andnext()throwsConcurrentModificationExceptionwhen the list changed.14 - Go:
maps.Keysin src/maps/iter.go at go1.23.0 is a push iterator. It ranges over the map and returns as soon asyieldreturnsfalse.15 - Every standard collection of Python, JavaScript, Java, C#, Rust and C++ gives its elements through the protocol of its language, so the loop statement of the language works on it.25712
References
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 5, Iterator (Intent, Also Known As, Motivation, Participants, Consequences, Implementation, Related Patterns)
- The Python Standard Library, Built-in Types, Python 3.14, Iterator Types, container.__iter__, iterator.__next__
- PEP 255: Simple Generators, Motivation
- The Python Language Reference, Expressions, Python 3.14, Yield expressions
- ECMA-262, ECMAScript 2026 Language Specification, 27.1.1.1 The Iterable Interface; 27.1.1.2 The Iterator Interface
- ECMA-262, ECMAScript 2026 Language Specification, Generator Objects
- Java SE 25 API, java.lang.Iterable, interface description; forEach(Consumer)
- Go 1.23 Release Notes, Changes to the language
- Go standard library, package iter, Iterators; Pulling Values; func Pull
- The Rust Standard Library, Module std::iter, Implementing Iterator
- C# language reference, yield statement, Execution of an iterator
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [range.range], the concept range
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), 26.8 Range generators [coro.generator], 26.8.1 Overview
- OpenJDK jdk-25+36 source, java/util/ArrayList.java, class Itr, lines 1036 to 1098
- Go go1.23.0 source, src/maps/iter.go, func Keys, lines 22 to 33
- Barbara Liskov, A History of CLU, HOPL-II, 1993, 3.10 Iterators
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag SG4FMR Edit this page History Report an error Markdown