Programming Search⌘K

Conceptintro

For-each loop

Also called for-each loop, foreach loop, foreach, enhanced for loop, for-in loop, for...of, range-based for loop, for range, enumeration loop, collection-controlled loop, iterator loop.

A for-each loop runs its body once for each element of a collection, with no index to manage. Under it, the language asks the collection for an iterator and calls it until it has no more elements.

Applies to
core-languages

Idea

Most loops visit each element of a list, a set, a map or a string. A for loop does this with an index: start at 0, read a[i], step i, stop at the length. A for-each loop leaves out the index. It names a variable, names the collection, and runs the body once with each element in the variable.

colors = ["red", "green", "blue"]
for color in colors:
    print(color)

# enumerate gives the index too, when the body needs it.
for i, color in enumerate(colors):
    print(i, color)

# A dictionary gives its keys; items() gives the pairs.
ages = {"ann": 31, "bob": 27}
for name, age in ages.items():
    print(name, age)

# What the for statement does: get an iterator, call next until StopIteration.
it = iter(colors)
while True:
    try:
        color = next(it)
    except StopIteration:
        break
    print("by hand:", color)
Output
red
green
blue
0 red
1 green
2 blue
ann 31
bob 27
by hand: red
by hand: green
by hand: blue

The first loop has no index and no length, so it cannot read past the end or skip an element. enumerate adds an index for the cases that need one. A dictionary loop can take the key and the value apart in the loop header. The last loop does by hand what the for statement does: it gets an iterator from the list and asks it for the next element until it raises StopIteration.

How it works

A loop over elements, not positions. Wikipedia calls this form an enumeration, "a loop intended to iterate over all the items of a collection"1. It is "not as flexible as a conditional loop; but it is more predictable"1: it ends when the elements end.

The iterator protocol under it. Each language turns a for-each loop into calls on an iterator. See iterators.

  • Python: the collection "is evaluated once; it should yield an iterable object. An iterator is created for that iterable"2, and the loop ends when the iterator is exhausted.
  • JavaScript: for...of "first calls the iterable's Symbol.iterator method, which returns an iterator, and then repeatedly calls the resulting iterator's next() method to produce the sequence of values"3. Arrays, strings, maps, sets and generators are iterable.
  • Java: in the enhanced for, "The type of the Expression must be an array type (§10.1) or a subtype of the raw type Iterable, or a compile-time error occurs"4.
  • C#: foreach works "for each element in an instance of the type that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface"5. A type with a GetEnumerator method also works, and the enumerator has "the public Current property and the public parameterless MoveNext method whose return type is bool"5.
  • Rust: "A for expression is a syntactic construct for looping over elements provided by an implementation of std::iter::IntoIterator"6.
  • Go: a for with a range clause "iterates through all entries of an array, slice, string or map, values received on a channel, integer values from zero to an upper limit [Go 1.22], or values passed to an iterator function's yield function [Go 1.23]"7.
  • C++: the range-based for is "a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container"8. It calls begin and end on the range.

The names. "Enumerations are sometimes called "for loops," for example in Zig and Rust"1. This can be confusing, because C, C++ and Java "use that term for the three-part for loop"1. "Other programming languages, such as Perl and C#, avoid this confusion by using the term "foreach loop.""1.

for...in is not for...of in JavaScript. "The for...in statement iterates over the enumerable string properties of an object, while the for...of statement iterates over values that the iterable object defines to be iterated over"3. On an array, for...in gives the indexes as strings, and "the for...in loop will return all enumerable properties, including those with non–integer names"9. Use for...of for the elements.

The order. "The order in which the items in the collection are iterated through depends on the programming language"1 and on the collection. A list gives its elements in order. In Go, "The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next"7, so a program that needs a fixed order sorts the keys first.

The loop variable. In most languages the loop variable gets a copy of the element or a reference to it, and the difference matters when the body changes it. Python assigns each element to the name, and an assignment to the name in the body does not change the list. Go copies each element of a slice into the variable. C++ copies with for (auto x : v) and refers to the element with for (auto& x : v). Rust moves the elements out of a vector with for x in v, borrows them with for x in &v and borrows them for change with for x in &mut v.

Changing the collection in the loop. The Python tutorial warns that "Code that modifies a collection while iterating over that same collection can be tricky to get right"10, and advises a loop over a copy or the building of a new collection. Java and C# throw an exception when a list changes during a for-each loop, Python raises an error when a dictionary changes size, and in C++ the iterator can become invalid, which is undefined behavior.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CAbsent
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the for...of and for...in loops of JavaScript, and the type of the loop variable comes from the iterable. No example file exists.
GoNative
RustNative
KotlinNativeKotlin has for (x in collection) over anything with an iterator() operator, and withIndex() adds the index. No example file exists because kotlinc is not installed.
SQLIdiomA query applies to each row of a set with no loop. Cursors in procedural extensions loop over the rows of a query.
BashNativeBash has for name in words, and for x in "${array[@]}" loops over the elements of an array. No example file exists.
PowerShellNativePowerShell has foreach ($x in $items) and the ForEach-Object cmdlet for pipelines. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no loops.
CSSDoes not applyCSS has no loops. A selector applies a rule to each matching element.
Regular expressionsDoes not applyA regular expression has no collections to loop over.
Language Verdict Mechanism
Python native for x in iterable:; enumerate, zip and dict.items(); the __iter__ and __next__ protocol
JavaScript native for (const x of iterable) over the Symbol.iterator protocol; for...in over property names
TypeScript native for...of of JavaScript; the element type comes from the iterable type
Java native the enhanced for (T x : expr) over an array or an Iterable
Kotlin native for (x in collection) over anything with an iterator() operator; withIndex()
C# native foreach (var x in e) over IEnumerable<T> or a GetEnumerator pattern; await foreach
Go native for i, v := range x over arrays, slices, strings, maps, channels, integers and iterator functions
Rust native for x in expr over IntoIterator; &v, &mut v and v borrow, change or move
C absent no for-each loop; an index or pointer loop with a known length or a sentinel
C++ native the range-based for (auto& x : range) over begin and end
Bash native for x in words; "${array[@]}" loops over the elements of an array
PowerShell native foreach ($x in $items) and the ForEach-Object cmdlet
SQL idiom a query works on each row of a set with no loop; cursors loop over rows in procedural code
Regex n/a no collections
HTML n/a no loops
CSS n/a no loops; a selector applies a rule to each matching element

All the general-purpose languages except C have a for-each loop, and they differ in the protocol under it and in what the loop variable holds. Java, C#, Kotlin, Python and JavaScript give a reference to each object, C++ and Go give a copy unless the code asks for more, and Rust makes the choice of move, borrow or change a part of the loop header.

The example files show these differences. Python loops over a dictionary and gets an error when the dictionary changes size. JavaScript compares for...of with for...in and loops over a Map and over the code points of a string. Java loops over an array and gets a ConcurrentModificationException from a list. C# takes tuples apart in the loop header, loops over an iterator method and gets an exception when a list changes. Go shows that the range variable is a copy, sorts map keys for a fixed order and loops over the runes of a string. Rust borrows, changes and moves a vector. C has no for-each loop and loops with a length or a sentinel. C++ uses references, structured bindings over a map and an init statement.

PythonGitHub
stock = {"apple": 3, "pear": 0, "plum": 5}
for name, count in stock.items():
    print(name, count)

# Deleting from a dictionary during the loop is an error.
try:
    for name in stock:
        if stock[name] == 0:
            del stock[name]
except RuntimeError as e:
    print("error:", e)

# Loop over a copy of the keys, or build a new dictionary.
stock = {"apple": 3, "pear": 0, "plum": 5}
for name in list(stock):
    if stock[name] == 0:
        del stock[name]
print(sorted(stock))
in_stock = {k: v for k, v in stock.items() if v > 0}
print(in_stock)
Output
apple 3
pear 0
plum 5
error: dictionary changed size during iteration
['apple', 'plum']
{'apple': 3, 'plum': 5}
  • Verdict: native. for name, count in stock.items() takes each pair apart in the header. The loop that deletes pear fails at the next step with a RuntimeError, because the dictionary changed size. list(stock) makes a copy of the keys, so the second loop can delete safely, and a comprehension builds a new dictionary with no deletes at all.
#include <map>
#include <print>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> words{"red", "green"};
    for (auto& w : words) w += "!";  // a reference changes the element
    for (auto w : words) w += "?";   // a copy changes nothing
    for (const auto& w : words) std::println("{}", w);

    // Structured bindings take each pair of the map apart.
    std::map<std::string, int> ages{{"bob", 27}, {"ann", 31}};
    for (const auto& [name, age] : ages) std::println("{} is {}", name, age);

    // An init statement declares the range in the loop header.
    int total = 0;
    for (std::vector nums{4, 5, 6}; int n : nums) total += n;
    std::println("total: {}", total);
}
Output
red!
green!
ann is 31
bob is 27
total: 15
  • Verdict: native. auto& binds to each element, so w += "!" changes the vector, and auto makes a copy, so w += "?" is lost. A std::map keeps its keys sorted, so ann comes first. The init statement keeps nums inside the loop.
JavaGitHub
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        int[] scores = {70, 85, 92};
        int total = 0;
        for (int s : scores) {
            total += s;
        }
        System.out.println("total: " + total);

        List<String> names = new ArrayList<>(List.of("ann", "cy", "bob", "dee"));
        try {
            for (String n : names) {
                if (n.length() == 2) {
                    names.remove(n);
                }
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("ConcurrentModificationException");
        }

        List<String> fresh = new ArrayList<>(List.of("ann", "cy", "bob", "dee"));
        fresh.removeIf(n -> n.length() == 2);
        System.out.println(fresh);
    }
}
Output
total: 247
ConcurrentModificationException
[ann, bob, dee]
  • Verdict: native. The enhanced for works on an array and on any Iterable. A remove on the list during the loop makes the hidden iterator fail at its next step with a ConcurrentModificationException. removeIf removes the elements safely in one call.
#include <stddef.h>
#include <stdio.h>

#define COUNT(a) (sizeof (a) / sizeof (a)[0])

int main(void) {
    int primes[] = {2, 3, 5, 7};
    int sum = 0;
    for (size_t i = 0; i < COUNT(primes); i++)
        sum += primes[i];
    printf("sum: %d\n", sum);

    /* A NULL at the end marks the last element. */
    const char *names[] = {"ann", "bob", NULL};
    for (const char **p = names; *p != NULL; p++)
        printf("name: %s\n", *p);

    /* A pointer from the start to one past the end. */
    for (int *p = primes, *end = primes + COUNT(primes); p != end; p++)
        *p *= 2;
    printf("%d %d %d %d\n", primes[0], primes[1], primes[2], primes[3]);
    return 0;
}
Output
sum: 17
name: ann
name: bob
4 6 10 14
  • Verdict: absent. C has no for-each loop, and an array passed to a function loses its length. The three loops are the usual substitutes: an index up to a length computed with sizeof, a pointer up to a NULL sentinel, and a pointer up to one past the end, the model for the iterators of C++.
var items = new List<(string Name, int Qty)> { ("tea", 2), ("cake", 1) };
foreach (var (name, qty) in items)
    Console.WriteLine($"{name} x{qty}");

// foreach works on any IEnumerable<T>, here an iterator method.
Console.WriteLine(string.Join(" ", Evens(8)));

var list = new List<int> { 1, 2, 3 };
try
{
    foreach (var x in list)
        if (x == 2) list.Add(4);
}
catch (InvalidOperationException)
{
    Console.WriteLine("InvalidOperationException: the list changed");
}

static IEnumerable<int> Evens(int limit)
{
    for (int i = 0; i <= limit; i += 2)
        yield return i;
}
Output
tea x2
cake x1
0 2 4 6 8
InvalidOperationException: the list changed
  • Verdict: native. foreach (var (name, qty) in items) takes each tuple apart. Evens is an iterator method, and yield return gives the elements one by one to the caller. An Add during the loop makes the enumerator of the list throw an InvalidOperationException at its next step.
JavaScriptGitHub
const arr = [10, 20, 30];
arr.extra = "x";
const values = [];
for (const v of arr) values.push(v);
const keys = [];
for (const k in arr) keys.push(k);
console.log("of:", values.join(","));
console.log("in:", keys.join(","));

// A Map gives [key, value] pairs in insertion order.
const m = new Map([["a", 1], ["b", 2]]);
for (const [key, value] of m) console.log(key, value);

// for...of on a string gives code points, not UTF-16 code units.
const s = "a😀";
const chars = [];
for (const ch of s) chars.push(ch);
console.log(s.length, chars.length);
Output
of: 10,20,30
in: 0,1,2,extra
a 1
b 2
3 2
  • Verdict: native. for...of uses the iterator of the array and gives the three values. for...in gives the property names as strings, and it includes the extra property. A Map gives pairs that the header takes apart, and a string gives whole code points, so the emoji counts as one element although length counts it as two.
package main

import (
	"fmt"
	"sort"
)

type point struct{ x, y int }

func main() {
	pts := []point{{1, 2}, {3, 4}}
	for _, p := range pts {
		p.x = 100 // changes a copy
		fmt.Println("copy:", p)
	}
	fmt.Println(pts)
	for i := range pts {
		pts[i].x *= 10 // changes the element
	}
	fmt.Println(pts)

	// Map order is not fixed, so sort the keys for stable output.
	ages := map[string]int{"bob": 27, "ann": 31, "cy": 5}
	keys := make([]string, 0, len(ages))
	for k := range ages {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		fmt.Println(k, ages[k])
	}

	// range over a string gives byte offsets and runes.
	for i, r := range "hé!" {
		fmt.Println(i, string(r))
	}
}
Output
copy: {100 2}
copy: {100 4}
[{1 2} {3 4}]
[{10 2} {30 4}]
ann 31
bob 27
cy 5
0 h
1 é
3 !
  • Verdict: native. for _, p := range pts copies each element into p, so the slice keeps its values, and the loop over the index changes the elements. The keys of a map come in no fixed order, so the code sorts them. Over a string, range gives the byte offset and the rune, so ! is at offset 3, after the two bytes of é.
RustGitHub
fn main() {
    let mut v = vec![1, 2, 3];

    // &v borrows each element.
    let mut sum = 0;
    for x in &v {
        sum += x;
    }
    println!("sum: {sum}");

    // &mut v borrows each element for change.
    for x in &mut v {
        *x *= 10;
    }
    println!("{v:?}");

    for (i, x) in v.iter().enumerate() {
        println!("{i}: {x}");
    }

    // v by value moves the elements into the loop; v cannot be used after it.
    let words = vec![String::from("a"), String::from("b")];
    for w in words {
        println!("owned {w}");
    }
}
Output
sum: 6
[10, 20, 30]
0: 10
1: 20
2: 30
owned a
owned b
  • Verdict: native. A for loop takes anything that implements IntoIterator. &v gives shared references, &mut v gives mutable references that the body changes through *x, and words by value moves each String into w, so a use of words after the loop would not compile.
  • The index. When the body needs the position too, use enumerate in Python, entries() in JavaScript, withIndex() in Kotlin, .iter().enumerate() in Rust or the first value of range in Go.
  • Several collections at once. zip in Python and Rust gives pairs from two collections, and stops at the end of the shorter one.
  • Destructuring. Python, JavaScript, C#, Rust and C++ can take a pair or a tuple apart in the loop header.
  • For-each methods. forEach in JavaScript and Java, and for_each in Rust, take a function and call it for each element. A break does not work in them. See higher-order functions.
  • Asynchronous loops. for await...of in JavaScript and await foreach in C# wait for each element of an asynchronous stream.

Pitfalls

  • Changing the collection. Adding or removing elements during the loop raises an error or skips elements. Loop over a copy, collect the changes and apply them after the loop, or use a method such as removeIf. See iterator invalidation.
  • A copy instead of the element. In Go and in C++ with auto, a change to the loop variable changes a copy, and the collection stays the same. Use the index in Go and auto& in C++.
  • for...in on arrays in JavaScript. It gives the keys as strings, and it includes other enumerable properties. Use for...of.
  • Map order. Do not depend on the order of a hash map. Sort the keys when the output must be stable.
  • A moved collection in Rust. for x in v moves v, so the code after the loop cannot use v. Loop over &v to keep it.
  • Temporaries in C++. In the range-based for, "If range-initializer returns a temporary, its lifetime is extended until the end of the loop"8, but in older C++ standards a temporary deeper in the expression, as in for (auto& x : make().items()), is destroyed before the body runs.

Cost

A for-each loop over an array or a vector compiles to the same code as an index loop in C++, Rust, Go, Java and C#, and compilers can remove bounds checks because the loop never leaves the collection. A loop over a linked list or a tree costs what its iterator costs. In Python, for x in xs is faster and clearer than for i in range(len(xs)) with xs[i] in the body, because it does no index arithmetic.

History

Many language families have a loop over the items of a collection. Wikipedia notes that "descendants of ALGOL use for", that "descendants of Fortran use do" and that "COBOL uses PERFORM VARYING"1. Perl and C# called it foreach. Java 5, released on 30 September 2004, added the "Enhanced for each loop", with "special syntax for iterating over each member of either an array or any Iterable"11.

References

  1. Loop (statement), Wikipedia, Enumeration
  2. Compound statements, The Python Language Reference, 8.3 The for statement
  3. for...of, MDN Web Docs, Description; Difference between for...of and for...in
  4. The Java Language Specification, Java SE 25 Edition, Chapter 14, 14.14.2 The enhanced for statement
  5. Iteration statements, C# language reference, The foreach statement
  6. Loops and other breakable expressions, The Rust Reference, Iterator loops
  7. The Go Programming Language Specification, For statements with range clause
  8. Range-based for loop, C++ reference, cppreference.com, Introduction; Temporary range initializer
  9. for...in, MDN Web Docs, Introduction; Array iteration and for...in
  10. More Control Flow Tools, The Python Tutorial, 4.2 for Statements
  11. Java version history, Wikipedia, J2SE 5.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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/0MTSVJ/text.yaml