Conceptcore
Iterator
Also called enumerator, iteration protocol.
An iterator gives the elements of a sequence one at a time and remembers its position between calls. A loop asks it for the next element until it says that no elements are left.
- Applies to
- core-languages
Idea
A program often visits the elements of a collection, one after the other. The collection can be a list, the lines of a file, the keys of a table or the nodes of a tree. Each kind of collection stores its elements in a different way, so each needs different code to find the next element. An iterator hides that code. It is an object that gives the elements one at a time and remembers where it is between calls. The code that uses the iterator knows only two operations: get the next element, and find out that no elements are left.4
With iterators, one loop statement works for every kind of collection. The for loop of Python, the for...of loop of JavaScript, the enhanced for of Java, foreach of C# and the for loop of Rust all take an iterable value and drive its iterator. Library functions such as sum, max or collect also take any iterable, so they do not need one version for each collection.
In Python, iter() asks a list for an iterator, and next() asks the iterator for one element. When no elements are left, next() raises StopIteration.2
colors = ["red", "green"]
it = iter(colors)
print(next(it))
print(next(it))
try:
next(it)
except StopIteration:
print("no more elements")
red
green
no more elements
The list does not change. The iterator holds the position, so two iterators over the same list move independently.
How it works
An iteration protocol has three parts. The iterable is the value that can be visited, such as a list. The iterator is a separate object that holds the state of one pass: a position, and often a reference to the iterable. The protocol is the set of methods that the loop statement calls. A loop statement first asks the iterable for an iterator, once. Then it asks the iterator for elements until the iterator signals the end.5
Each language names these operations in its own way. The table shows the names.
| Language | Get an iterator | Get the next element | End of the elements |
|---|---|---|---|
| Python | iter(x), which calls x.__iter__() |
next(it), which calls it.__next__() |
__next__ raises StopIteration2 |
| JavaScript, TypeScript | x[Symbol.iterator]() |
it.next() returns { value, done } |
done is true78 |
| Java | x.iterator() |
it.hasNext(), then it.next() |
hasNext() returns false15 |
| Kotlin | x.iterator() |
it.hasNext(), then it.next() |
hasNext() returns false35 |
| C#, PowerShell | x.GetEnumerator() |
e.MoveNext(), then e.Current |
MoveNext() returns false18 |
| Rust | x.into_iter() |
it.next() returns Option<T> |
next() returns None25 |
| C++ | begin(x) and end(x) |
*it reads, ++it moves |
it == end30 |
| Go | the value is a function | the function calls yield(v) |
the function returns21 |
A loop statement is a short form of a while loop over these calls. The Java specification gives the enhanced for statement as a basic for loop that calls iterator(), hasNext() and next().16 The C++ standard defines the range-based for statement as a loop from begin to end with ++.30 The Rust Reference defines a for loop as a call of IntoIterator::into_iter and a loop that calls next() until None.29 In C#, foreach uses any type that has a suitable GetEnumerator method, MoveNext method and Current property, even when the type does not implement IEnumerable.17 The Python for statement written as a while loop looks like this:
colors = ["red", "green"]
it = iter(colors)
while True:
try:
color = next(it)
except StopIteration:
break
print(color)
red
green
The iterator and the iterable can be one object. In Python, the __iter__ method of an iterator returns the iterator itself, so an iterator can go where an iterable is expected.1 A list is a container, not an iterator: it makes a fresh iterator for each call of iter(). An iterator has only one pass. After it is exhausted, it keeps signalling the end, so a second loop over it sees no elements.4
The end rule is not the same everywhere. Python says that an iterator that has raised StopIteration must raise it on each later call, and an iterator that does not is broken.2 ECMAScript says that a next call after done: true should also return done: true, but the language does not enforce this.8 Rust allows an iterator to return Some again after None, and TryIter is one that does.25 Code that needs the end to stay the end must not assume it.
An iterator can also be told that the loop stopped early. In JavaScript, an iterator can have an optional return method. When a for...of loop ends through break, return or an exception, the language calls it, so the iterator can close a file or free other resources.98 The JavaScript example shows this. In C#, foreach is defined as a while loop inside try and finally, and the finally block disposes of the enumerator.17
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | |
| SQL | Does not apply | A query describes a result set, and the database decides how to visit the rows. |
| Bash | Idiom | |
| PowerShell | Native | |
| HTML | Does not apply | Markup has no loops. |
| CSS | Does not apply | Style rules have no loops. |
| Regular expressions | Does not apply | A pattern has no loops over values. |
The example files show the same countdown iterator in each language. The table gives the verdict for each tier 1 language.
| Language | Verdict | Form |
|---|---|---|
| Python | native | __iter__ and __next__; generator functions |
| JavaScript | native | Symbol.iterator and next(); generator functions; iterator helpers |
| TypeScript | native | as JavaScript, with the types Iterable<T> and Iterator<T> |
| Java | native | Iterable<T> and Iterator<T>; enhanced for |
| C | idiom | a struct that holds the position and a next function |
| C++ | native | iterator types with begin and end; range-based for |
| C# | native | IEnumerable<T> and IEnumerator<T>; foreach; yield return |
| Go | native | functions of type iter.Seq and iter.Seq2; range over a function |
| Rust | native | the trait Iterator; for over IntoIterator |
| Kotlin | native | Iterable<T> and Iterator<T>; Sequence<T> for lazy chains |
| PowerShell | native | .NET enumerators; the pipeline enumerates its input |
| Bash | idiom | for over an expanded word list; while read over a stream |
| SQL | n/a | a query describes a result set, not a loop |
| Regex | n/a | a pattern has no loops over values |
| HTML/CSS | n/a | markup and style rules have no loops |
C has no iterator protocol and no loop statement that calls one. A pointer is the iterator of an array. For other data, the usual form is a struct that holds the position and a function that returns the next element, as the C example shows. Nothing in the language connects the two, and nothing checks that the data stays valid.
Bash has no iterator objects. The for loop expands its words first and then runs the body once for each word in the resulting list.37 To process a stream item by item, a while read loop reads one line at a time from a pipe, as the Bash example shows.
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
for n in Countdown(3):
print(n)
it = iter(["a", "b"])
print(next(it), next(it))
print(next(it, "end"))
3
2
1
a b
end
- Verdict: native. An iterator is an object with
__next__, and an iterable is an object whose__iter__returns an iterator. Theforstatement callsiter()once and thennext()untilStopIteration. - An iterator's own
__iter__returnsself, so an iterator can go where an iterable is expected. next(it, default)returns the default instead of raisingStopIterationwhen the iterator is exhausted.- A generator function (a
defwithyield) makes an iterator with less code. The class above shows the protocol that the generator implements for you.
#include <iostream>
#include <vector>
struct Countdown {
int start;
struct iterator {
int current;
int operator*() const { return current; }
iterator& operator++() {
--current;
return *this;
}
bool operator!=(const iterator& other) const { return current != other.current; }
};
iterator begin() const { return {start}; }
iterator end() const { return {0}; }
};
int main() {
for (int n : Countdown{3}) {
std::cout << n << '\n';
}
std::vector<int> v{10, 20, 30};
for (auto it = v.begin(); it != v.end(); ++it) {
std::cout << *it << ' ';
}
std::cout << '\n';
}
3
2
1
10 20 30
- Verdict: native. A C++ iterator is a position, not a stream. A range has
begin()andend(), and the loop compares the two positions, reads with*and moves with++. - The range-based
forstatement is a short form of the second loop. It uses onlybegin,end,!=,++and*, so the small struct above is enough. - Iterators of
std::vectorare random access:it + 2andit[1]are valid. Iterators ofstd::listare bidirectional only. - Most operations that change a container invalidate some of its iterators. Using an invalid iterator is undefined behaviour (see Pitfalls on the concept page).
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class Main {
record Countdown(int start) implements Iterable<Integer> {
public Iterator<Integer> iterator() {
return new Iterator<>() {
private int current = start;
public boolean hasNext() {
return current > 0;
}
public Integer next() {
if (current <= 0) {
throw new NoSuchElementException();
}
return current--;
}
};
}
}
public static void main(String[] args) {
for (int n : new Countdown(3)) {
System.out.println(n);
}
Iterator<String> it = List.of("a", "b").iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
3
2
1
a
b
- Verdict: native. A class implements
Iterable<T>, and itsiterator()method returns anIterator<T>withhasNext()andnext(). - The enhanced
forstatement is a short form of thewhileloop above: it callsiterator()once, thenhasNext()andnext()for each element. - The iterators of
ArrayListare fail-fast. A change to the collection that does not go through the iterator makes the next call throwConcurrentModificationException(see Pitfalls on the concept page). Iterator<Integer>holds boxedIntegervalues. The loop unboxes each one intoint n.
#include <stdbool.h>
#include <stdio.h>
struct countdown {
int current;
};
static bool countdown_next(struct countdown *it, int *out) {
if (it->current <= 0) {
return false;
}
*out = it->current;
it->current--;
return true;
}
int main(void) {
struct countdown it = {3};
int n;
while (countdown_next(&it, &n)) {
printf("%d\n", n);
}
const char *words[] = {"a", "b", NULL};
for (const char **p = words; *p != NULL; p++) {
printf("%s\n", *p);
}
return 0;
}
3
2
1
a
b
- Verdict: idiom. C has no iterator protocol and no loop that calls one. The usual form is a struct that holds the position and a
nextfunction that returnsfalseat the end and writes the element through a pointer. - A pointer is the iterator of an array. The second loop walks an array of strings that ends with
NULL. - The caller owns the struct, so the iterator needs no heap allocation. Nothing checks that the data under the iterator stays valid.
using System;
using System.Collections.Generic;
static IEnumerable<int> Countdown(int start)
{
for (int i = start; i > 0; i--)
{
Console.WriteLine($"yield {i}");
yield return i;
}
}
IEnumerable<int> numbers = Countdown(2);
Console.WriteLine("nothing ran yet");
foreach (int n in numbers)
{
Console.WriteLine(n);
}
using IEnumerator<string> e = new List<string> { "a", "b" }.GetEnumerator();
while (e.MoveNext())
{
Console.WriteLine(e.Current);
}
nothing ran yet
yield 2
2
yield 1
1
a
b
- Verdict: native. An enumerable has
GetEnumerator(). The enumerator starts before the first element;MoveNext()moves it and returnsfalseat the end, andCurrentgives the element. - A method with
yield returnis an iterator method. The call does not run the body. The body runs up to eachyield returnwhenMoveNext()is called, sonothing ran yetcomes first. foreachcallsDispose()on the enumerator when the loop ends. Theusingdeclaration does the same for the manual loop.- A change to a
List<T>invalidates its enumerators. The nextMoveNext()throwsInvalidOperationException(see Pitfalls on the concept page).
class Countdown {
constructor(start) {
this.start = start;
}
[Symbol.iterator]() {
let current = this.start;
return {
next() {
if (current <= 0) {
return { done: true, value: undefined };
}
return { done: false, value: current-- };
},
return() {
console.log("closed");
return { done: true, value: undefined };
},
};
}
}
for (const n of new Countdown(3)) {
console.log(n);
}
for (const n of new Countdown(3)) {
if (n === 2) {
break;
}
console.log(n);
}
console.log([...new Countdown(2)]);
3
2
1
3
closed
[ 2, 1 ]
- Verdict: native. An iterable has a method under the key
Symbol.iterator. The method returns an iterator, an object whosenext()returns{ done, value }. for...of, spread syntax, destructuring andArray.fromall use the same protocol.- The optional
return()method runs when the loop stops early. Herebreakcalls it and printsclosed. A loop that runs to the end does not call it. - A generator function (
function*) makes an iterator with less code.
class Countdown implements Iterable<number> {
readonly start: number;
constructor(start: number) {
this.start = start;
}
[Symbol.iterator](): Iterator<number> {
let current = this.start;
return {
next(): IteratorResult<number> {
if (current <= 0) {
return { done: true, value: undefined };
}
return { done: false, value: current-- };
},
};
}
}
for (const n of new Countdown(3)) {
console.log(n);
}
const tens: number[] = Iterator.from(new Countdown(5))
.filter((n) => n % 2 === 1)
.map((n) => n * 10)
.toArray();
console.log(tens);
3
2
1
[ 50, 30, 10 ]
- Verdict: native. TypeScript uses the JavaScript protocol and adds the types
Iterable<T>,Iterator<T>andIteratorResult<T>. Iterator.fromwraps an iterable so that the iterator helper methods (filter,map,take,toArray) are available. The helpers are lazy: each one pulls one value at a time from the one before it.- The type checker checks only the shapes. It does not check that
next()keeps returningdone: trueafter the end.
package main
import (
"fmt"
"iter"
)
func Countdown(start int) iter.Seq[int] {
return func(yield func(int) bool) {
for i := start; i > 0; i-- {
if !yield(i) {
fmt.Println("stopped")
return
}
}
}
}
func main() {
for n := range Countdown(3) {
fmt.Println(n)
}
for n := range Countdown(5) {
if n == 4 {
break
}
fmt.Println(n)
}
next, stop := iter.Pull(Countdown(2))
defer stop()
for {
n, ok := next()
if !ok {
break
}
fmt.Println("pulled", n)
}
}
3
2
1
5
stopped
pulled 2
pulled 1
- Verdict: native. An iterator is a function of type
iter.Seq[V],func(yield func(V) bool). Arangeloop over it gives the loop body to the iterator asyield. - This is a push iterator: the iterator calls the loop. When the loop body runs
break,yieldreturnsfalse, and the iterator must return. iter.Pullturns a push iterator into a pull iterator, anextfunction and astopfunction. Callstopwhen you finish early.rangealso works over slices, maps, strings, channels and integers. The order of a map is not specified (see Pitfalls on the concept page).
struct Countdown {
current: u32,
}
impl Iterator for Countdown {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.current == 0 {
return None;
}
self.current -= 1;
Some(self.current + 1)
}
}
fn main() {
let countdown = Countdown { current: 3 };
for n in countdown {
println!("{n}");
}
let tens: Vec<u32> = Countdown { current: 5 }
.filter(|n| n % 2 == 1)
.map(|n| n * 10)
.collect();
println!("{tens:?}");
let mut it = vec!["a", "b"].into_iter();
println!("{:?} {:?} {:?}", it.next(), it.next(), it.next());
}
3
2
1
[50, 30, 10]
Some("a") Some("b") None
- Verdict: native. A type implements the trait
Iteratorwith one required method,next(&mut self) -> Option<Self::Item>.Nonemeans the end. - A
forloop callsIntoIterator::into_iteron its value. So it takes aVecby value, andfor x in &vborrows it. - Adapters such as
filterandmapare lazy. They return other iterators, and nothing runs until a consumer such ascollectorforpulls values. - The borrow checker rejects a change to a collection while an iterator borrows it (see Pitfalls on the concept page).
class Countdown(private val start: Int) : Iterable<Int> {
override fun iterator(): Iterator<Int> = object : Iterator<Int> {
private var current = start
override fun hasNext() = current > 0
override fun next(): Int {
if (current <= 0) throw NoSuchElementException()
return current--
}
}
}
fun main() {
for (n in Countdown(3)) {
println(n)
}
val tens = Countdown(5).asSequence()
.filter { it % 2 == 1 }
.map { it * 10 }
.toList()
println(tens)
}
3
2
1
[50, 30, 10]
- Verdict: native. A
forloop works on any value with anoperator fun iterator()whose result hasnext()andhasNext(). ImplementingIterable<T>is the usual way. - The compiler turns a
forloop over a range or an array into an index loop, with no iterator object. - Operations on an
Iterableare eager and make a list after each step.asSequence()makes the chain lazy, so each element goes throughfilterandmapbefore the next one starts. - An iterator cannot go back to the start. To iterate again, ask the collection for a fresh iterator.
items=(three two one)
for item in "${items[@]}"; do
echo "$item"
done
printf '%s\n' 3 2 1 | while IFS= read -r line; do
echo "line $line"
done
three
two
one
line 3
line 2
line 1
- Verdict: idiom. Bash has no iterator objects and no way to define one. The
forloop expands its word list in full and then runs the body once for each word. - To process a stream one item at a time, read lines in a
while readloop. Eachreadtakes the next line from the pipe. - The quotes in
"${items[@]}"keep each element as one word. Without them, an element with a space becomes two words. - Each command of a pipeline runs in its own subshell, so variables that the
whileloop sets are lost when the loop ends. Thelastpipeshell option, with job control off, lets the shell run the last command itself.
$e = @(3, 2, 1).GetEnumerator()
while ($e.MoveNext()) {
Write-Output $e.Current
}
foreach ($n in 'a', 'b') {
Write-Output $n
}
$table = @{ one = 1; two = 2 }
Write-Output (@(1, 2, 3) | Measure-Object).Count
Write-Output ($table | Measure-Object).Count
Write-Output ($table.GetEnumerator() | Measure-Object).Count
3
2
1
a
b
3
1
2
- Verdict: native. PowerShell uses the .NET enumerator protocol:
GetEnumerator(),MoveNext()andCurrent. - The pipeline enumerates any value that implements
IEnumerableand sends the items one at a time. So the array gives three objects toMeasure-Object. - A hashtable is an exception. The pipeline sends it as one object, so the count is 1. Call
GetEnumerator()to send its entries one at a time. - A string is also sent as one object, not as a sequence of characters.
Variations and related ideas
- External and internal iterators. With an external iterator, the caller asks for each element. The iterators of Python, Java, C#, Rust and C++ work this way. With an internal iterator, the iterator calls the loop body for each element. Go iterator functions work this way: the loop body becomes the
yieldfunction, andyieldreturnsfalsewhen the loop wants to stop.23 The Go documentation calls these push iterators, anditer.Pullturns one into a pull iterator with anextfunction and astopfunction.24 An external iterator can walk two sequences side by side. An internal iterator cannot, which was a limit of the iterators of CLU.41 - Generators. Writing an iterator class by hand means storing the position in fields. A generator function stores it in a suspended call: the body runs up to a
yield, gives a value, and continues from there on the next request. In C#, a call of a method withyield returndoes not run the body. The body runs up to the firstyield returnwhen the caller asks for the first element.20 The C# example shows this order. - Lazy chains. Adapters such as
map,filterandtakecan wrap an iterator in another iterator. No element is computed until a consumer asks for one. Rust adapters are lazy,26 JavaScript iterator helpers are lazy transformations of a source iterator,10 and Kotlin sequences process each element through the whole chain before the next element starts.34 - Infinite iterators. An iterator need not end. The Rust range
0..never returnsNone, so a program must limit it with an adapter such astake. A consumer that reads to the end, such asmin, never returns on an infinite iterator.27 - Iterator categories in C++. A C++ iterator is a position that generalizes a pointer. The standard defines six categories: input, output, forward, bidirectional, random access and contiguous. An input iterator allows one pass, and a forward iterator allows several.32
- Cursors. A database cursor gives the rows of a result set one at a time and plays the role of an iterator for a query. The SQL language itself describes the result, not the loop.
- Recursion. A recursive function visits a tree with the call stack as its state. An iterator over the same tree must keep an explicit stack of the nodes that are left. A generator can use recursion inside and still give one node at a time. See Recursion.
- Async iterators. When each element comes from input and output, the call that gets the next element can return a future or a promise, and the loop awaits it. See Async/await.
Pitfalls
Removing items while you loop skips items
A list iterator holds an index. When the loop removes the element at that index, the elements after it move one place back. The iterator then moves forward and skips the element that took the old place. The Python tutorial says that code that changes a collection while it iterates over it can be tricky.6
This code runs but gives a wrong answer on purpose.
numbers = [1, 2, 2, 3]
for n in numbers:
if n == 2:
numbers.remove(n)
print(numbers)
[1, 2, 3]
The fix is to make a fresh list, or to loop over a copy.6
numbers = [1, 2, 2, 3]
numbers = [n for n in numbers if n != 2]
print(numbers)
[1, 3]
A dictionary detects some changes. A loop over a dictionary that adds or deletes keys can raise RuntimeError, or it can fail to visit all entries.3 Loop over list(ages), a copy of the keys, to delete safely.
This code raises RuntimeError, on purpose.
ages = {"ana": 31, "bo": 17}
for name in ages:
if ages[name] < 18:
del ages[name]
A fail-fast iterator does not catch every change
The iterators of java.util.ArrayList are fail-fast. When the list changes in structure during the loop, by any means other than the iterator's own remove or add, the next call of next() throws ConcurrentModificationException.1314
This code raises ConcurrentModificationException, on purpose.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4));
for (Integer n : numbers) {
if (n == 2) {
numbers.remove(n);
}
}
System.out.println(numbers);
}
}
The check is not guaranteed. The documentation says that it is wrong to write a program that depends on this exception.13 When the loop removes the second-to-last element, hasNext() returns false at once. The loop ends with no exception, and it never visits the last element.
This code runs but gives a wrong answer on purpose.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3));
List<Integer> seen = new ArrayList<>();
for (Integer n : numbers) {
seen.add(n);
if (n == 2) {
numbers.remove(n);
}
}
System.out.println("seen " + seen + ", left " + numbers);
}
}
seen [1, 2], left [1, 3]
The fix is to remove through the iterator, or to call removeIf.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4));
Iterator<Integer> it = numbers.iterator();
while (it.hasNext()) {
if (it.next() == 2) {
it.remove();
}
}
System.out.println(numbers);
}
}
[1, 3, 4]
In C#, a change to a List<T> invalidates its enumerators, and the next MoveNext throws InvalidOperationException.18
This code raises InvalidOperationException, on purpose.
using System;
using System.Collections.Generic;
var numbers = new List<int> { 1, 2, 3 };
foreach (int n in numbers)
{
if (n == 1)
{
numbers.Add(4);
}
}
Console.WriteLine(numbers.Count);
An invalid iterator in C++ is undefined behaviour
A C++ iterator of a std::vector points into the storage of the vector. When push_back must grow the storage, it moves the elements, and all iterators of the vector become invalid. When it does not grow, the iterators at and after the insertion point become invalid. erase invalidates the iterators at and after the erased element.31 The range-based for loop keeps its iterators across the body,30 so a push_back inside the loop can leave the loop reading freed memory. The program compiles, and AddressSanitizer reports the error at run time.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3};
for (int n : v) {
if (n == 1) {
v.push_back(4);
}
std::cout << n << '\n';
}
}
Rust rejects the same program at compile time. The loop borrows v, and push needs a second, mutable borrow while the first is still alive.
This code does not compile, on purpose. The error is E0502.
fn main() {
let mut v = vec![1, 2, 3];
for n in &v {
if *n == 1 {
v.push(4);
}
}
println!("{v:?}");
}
The fix in both languages is to collect the changes in a second container and apply them after the loop, or to loop over indexes and read the length again on each pass.
An exhausted iterator looks empty
An iterator has one pass. A second loop over the same iterator sees no elements, and no error tells you so. The Python glossary says that an iterator used for a second pass looks like an empty container.4 Some functions return iterators, not lists. In Python, map is one of them, as the example shows. In Go, some iterator functions read from a stream and can walk it only once.23
This code runs but gives a wrong answer on purpose.
squares = map(lambda n: n * n, [1, 2, 3])
print(sum(squares))
print(max(squares, default=None))
14
None
The fix is to store the values in a list when you need more than one pass.
squares = list(map(lambda n: n * n, [1, 2, 3]))
print(sum(squares))
print(max(squares, default=None))
14
9
A lazy adapter does nothing until something consumes it
An adapter only builds an iterator. If nothing pulls values from that iterator, the closure in it never runs. The Rust documentation shows this mistake: a map used for its side effects prints nothing, and the compiler warns that iterators are lazy and do nothing unless consumed.26
This code runs but gives a wrong answer on purpose.
fn main() {
let v = vec![1, 2, 3];
v.iter().map(|n| println!("{n}"));
println!("done");
}
done
Use a for loop for side effects. Use map to compute values that a consumer such as collect or sum reads.
Map order is not a stable order
The Go specification does not say in which order a range loop visits the entries of a map. It also says that the order is not guaranteed to be the same from one loop to the next.21 Code that prints a map in a loop, or that compares two results, gives different output on different runs. Sort the keys when the order matters.
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
ages := map[string]int{"cy": 25, "ana": 31, "bo": 17}
for _, name := range slices.Sorted(maps.Keys(ages)) {
fmt.Println(name, ages[name])
}
}
ana 31
bo 17
cy 25
maps.Keys returns an iterator, and slices.Sorted reads it to the end and returns a sorted slice.
Cost
- One call for each element. A loop over an iterator makes at least one call for each element:
__next__in Python,hasNextandnextin Java and Kotlin,MoveNextandCurrentin C#. The Java enhancedforstatement makes these calls through theIteratorinterface.16 - Inlined adapters. In Rust and C++, each iterator and each adapter is a distinct type, so the compiler knows which
nextor++runs and can inline it. The Rust book calls iterators a zero-cost abstraction: a chain of adapters compiles to roughly the same code as a hand-written loop.28 The C++ standard defines iterators as a generalization of pointers, and a contiguous iterator works like a pointer into an array.32 - Laziness. A lazy chain holds one element at a time and builds no intermediate collection. An eager chain, such as Kotlin operations on an
Iterable, makes a full list after each step. The Kotlin documentation also says that the laziness of sequences has its own overhead, which can be significant for small collections or small computations.34 - Loops with no iterator object. The Kotlin compiler turns a
forloop over a range or an array into an index loop.35 A Pythonforloop over a list still makes an iterator object for the list.5 - Boxing. The Java type
Iterator<Integer>returns objects, notintvalues, so a loop over aList<Integer>reads one boxed object for each element.15
History
- 1975 and 1977. The CLU group learned of the generators of Alphard during a visit to Carnegie Mellon University in the summer of 1975. Russ Atkinson then designed the CLU iterator, a single procedure that yields its results one at a time to the body of a
forstatement.41 An Alphard generator was a group of operations, while a CLU iterator was one operation. Both designs were published in 1977.3839 - 1981. Ralph Griswold, David Hanson and John Korb described the generators of the Icon language.40
- 1995. Alexander Stepanov and Meng Lee described the Standard Template Library for C++. Its iterators are a generalization of pointers, and the report defines five categories of them.42 The C++ standard later added a sixth category, contiguous iterators.32
- 2001. PEP 234 by Ka-Ping Yee and Guido van Rossum defined the iterator protocol of Python: the built-in
iter(), the__iter__method, an iterator method callednext()and theStopIterationexception.1 In the Python 3.14 documentation, that method is__next__.2 - 2015. ECMAScript 2015 added the iteration protocols, the iterable interface and the iterator interface, to JavaScript.11
- 2024. Go 1.23, released on 13 August 2024, let
rangeloop over iterator functions.2243 - 2025. ECMAScript 2025 added iterator helpers such as
Iterator.prototype.map.12
References
- PEP 234: Iterators, Ka-Ping Yee and Guido van Rossum, Python API Specification
- The Python Standard Library, Built-in Types, Python 3.14, Iterator Types, iterator.__iter__ and iterator.__next__
- The Python Standard Library, Built-in Types, Python 3.14, Dictionary view objects
- Python Glossary, Python 3.14, iterator
- The Python Language Reference, Compound statements, Python 3.14, 8.3 The for statement
- The Python Tutorial, More Control Flow Tools, Python 3.14, 4.2 for Statements
- ECMA-262, ECMAScript 2026 Language Specification, 27.1.1.1 The Iterable Interface
- ECMA-262, ECMAScript 2026 Language Specification, 27.1.1.2 The Iterator Interface; 27.1.1.5 The IteratorResult Interface
- ECMA-262, ECMAScript 2026 Language Specification, 7.4.11 IteratorClose
- ECMA-262, ECMAScript 2026 Language Specification, 27.1.2 Iterator Helper Objects
- ECMA-262, 6th Edition, ECMAScript 2015 Language Specification, June 2015, 25.1 Iteration
- ECMA-262, ECMAScript 2025 Language Specification, Iterator.prototype.map
- Java SE 25 API, java.util.ArrayList, class description, fail-fast iterators
- Java SE 25 API, java.util.ConcurrentModificationException, class description
- Java SE 25 API, java.util.Iterator, interface description and method summary
- The Java Language Specification, Java SE 25 Edition, 14.14.2 The enhanced for statement
- C# language specification, Statements, 13.9.5 The foreach statement; 13.9.5.2 Synchronous foreach
- .NET API, List<T>.GetEnumerator Method, Remarks
- .NET API, IEnumerator<T> Interface, Remarks
- C# language reference, yield statement, Execution of an iterator
- The Go Programming Language Specification, For statements with range clause
- Go 1.23 Release Notes, Changes to the language
- Go standard library, package iter, Iterators; Single-Use Iterators
- Go standard library, package iter, Pulling Values; func Pull
- The Rust Standard Library, Module std::iter, Iterator
- The Rust Standard Library, Module std::iter, Laziness
- The Rust Standard Library, Module std::iter, Infinity
- The Rust Programming Language, 13.4 Comparing Performance, Loops vs. Iterators
- The Rust Reference, Loops and other breakable expressions, Iterator loops, rules expr.loop.for.intro and expr.loop.for.desugar
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [stmt.ranged], paragraph 1
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [vector.modifiers], paragraphs 2 and 3
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [iterator.requirements.general], paragraphs 1 and 2
- Kotlin documentation, Iterators, Iterators
- Kotlin documentation, Sequences, introduction, Iterable and Sequence processing
- Kotlin documentation, Conditions and loops, Iterators
- PowerShell documentation, about_Pipelines, One-at-a-time processing
- Bash Reference Manual, 3.2.5.1 Looping Constructs, for
- Barbara Liskov, Alan Snyder, Russell Atkinson and Craig Schaffert, Abstraction mechanisms in CLU, Communications of the ACM 20(8), 1977, iterators and the for statement
- Mary Shaw, William A. Wulf and Ralph L. London, Abstraction and verification in Alphard, defining and specifying iteration and generators, Communications of the ACM 20(8), 1977, generators and the for statement of Alphard
- Ralph E. Griswold, David R. Hanson and John T. Korb, Generators in Icon, ACM Transactions on Programming Languages and Systems 3(2), 1981, the paper as a whole
- Barbara Liskov, A History of CLU, HOPL-II, 1993, 3.10 Iterators
- Alexander Stepanov and Meng Lee, The Standard Template Library, Hewlett-Packard Laboratories, October 31, 1995, 5 Iterators
- Go Release History, go1.23.0
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 TPCCXM Edit this page History Report an error Markdown