Conceptadvanced
Iterator invalidation
Also called iterator invalidation, invalidated iterator, concurrent modification, ConcurrentModificationException, fail-fast iterator, modifying a collection while iterating, collection was modified, dictionary changed size during iteration, dangling iterator.
An iterator is invalidated when its collection changes in a way that the iterator cannot follow. Languages throw an error, skip elements, have undefined behavior or reject the code at compile time.
- Applies to
- core-languages
Idea
A loop over a list removes the elements that it does not want. The loop looks right, but it skips elements, or it stops with an error, or in C++ it reads freed memory. The loop holds an iterator, a position in the list, and the removal moves the elements under it. The iterator is invalidated: it no longer points where the loop thinks it points.
# Removing from a list while looping over it skips elements.
nums = [1, 2, 2, 3, 4]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print("in place:", nums)
# Loop over a copy, or build a new list.
nums = [1, 2, 2, 3, 4]
for n in nums[:]:
if n % 2 == 0:
nums.remove(n)
print("over a copy:", nums)
print("new list:", [n for n in [1, 2, 2, 3, 4] if n % 2 != 0])
# A dictionary checks its size and raises an error.
ages = {"ann": 31, "bob": 17, "cy": 12}
try:
for name in ages:
if ages[name] < 18:
del ages[name]
except RuntimeError as e:
print("RuntimeError:", e)
ages = {"ann": 31, "bob": 17, "cy": 12}
for name in list(ages):
if ages[name] < 18:
del ages[name]
print(ages)
in place: [1, 2, 3]
over a copy: [1, 3]
new list: [1, 3]
RuntimeError: dictionary changed size during iteration
{'ann': 31}
The first loop removes the first 2, and the list moves the second 2 into its place. The loop goes on to the next position, so it never sees the second 2, and the 4 is removed only because it comes later. The loop over the copy nums[:] sees all five elements. The dictionary notices that its size changed and raises an error, and the loop over list(ages) takes the keys first.
How it works
Why iterators break. An iterator is a position in a collection, often a pointer or an index. A change to the collection can move the elements, free the memory that holds them, or rebuild a hash table. The Rust book gives the reason for a vector: "adding a new element onto the end of the vector might require allocating new memory and copying the old elements to the new space, if there isn't enough room to put all the elements next to each other where the vector is currently stored. In that case, the reference to the first element would be pointing to deallocated memory"1.
C++: rules for each container. C++ lists, for each container, which changes invalidate which iterators. cppreference says that "Read-only methods never invalidate iterators or references. Methods which modify the contents of a container may invalidate iterators and/or references"2. For a vector, push_back invalidates all iterators when it must grow: "If after the operation the new size() is greater than old capacity() a reallocation takes place, in which case all iterators (including the end() iterator) and all references to the elements are invalidated. Otherwise only the end() iterator is invalidated"3. A list keeps its other iterators valid, and an erasure invalidates only the erased elements2. The use of an invalid iterator is undefined behavior: the program can crash, print garbage or seem to work.
Java: fail-fast iterators. The iterators of ArrayList "are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException"4. A structural modification "is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification"4. The check is not a promise: "Fail-fast iterators throw ConcurrentModificationException on a best-effort basis"4. The name of the exception is misleading. "Note that this exception does not always indicate that an object has been concurrently modified by a different thread"5: one thread that changes a list in its own for-each loop gets it too.
C#: the enumerator is invalidated. In .NET, "An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or IEnumerator.Reset throws an InvalidOperationException"6.
Python: a check for dictionaries and sets, none for lists. "Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries"7. A list has no check, so a loop that removes elements skips some, as the example shows. The tutorial advises: "Code that modifies a collection while iterating over that same collection can be tricky to get right. Instead, it is usually more straight-forward to loop over a copy of the collection or to create a new collection"8.
JavaScript: defined but surprising. The array methods such as forEach have exact rules. "only indexes between 0 and arrayLength - 1 are visited, where arrayLength is the length of the array at the time the array method was first called"9, so elements added at the end are not visited, and "Removed elements are not visited"9. MDN still warns that such changes "frequently lead to hard-to-understand code and are generally to be avoided"9.
Go: defined for maps. The Go specification says what happens when a range loop changes a map: "If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced. If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped"10. For a slice, "The range expression x is evaluated before beginning the loop"10, so an append in the body does not make the loop longer.
Rust: rejected at compile time. Rust's borrow rules forbid the change. "Iterating over a vector, whether immutably or mutably, is safe because of the borrow checker's rules"1. A for loop over &v borrows the vector, and "The reference to the vector that the for loop holds prevents simultaneous modification of the whole vector"1. The compiler reports error E0502, "cannot borrow v as mutable because it is also borrowed as immutable"1.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Absent | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the arrays, maps and sets of JavaScript, so a change during a loop follows the rules of JavaScript. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin uses the collections of Java, so a change to a list in a for loop throws ConcurrentModificationException, and MutableIterator.remove and removeAll are safe. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A query has no iterators. UPDATE and DELETE work on a set of rows. |
| Bash | Does not apply | Bash has no iterators. The loop for x in "${a[@]}" expands the array once, before the loop starts. |
| PowerShell | Native | A foreach loop over a .NET list uses its enumerator, so a change to the list fails with an error that the collection was modified. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no collections or loops. |
| CSS | Does not apply | CSS has no collections or loops. |
| Regular expressions | Does not apply | A regular expression has no collections. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | RuntimeError when a dict or set changes size during a loop; no check for lists |
| JavaScript | native | array methods visit the indexes below the first length; Map and Set iterators see new entries |
| TypeScript | native | the rules of JavaScript |
| Java | native | fail-fast iterators throw ConcurrentModificationException; Iterator.remove and removeIf are safe |
| Kotlin | native | the collections of Java; MutableIterator.remove and removeAll |
| C# | native | InvalidOperationException on the next MoveNext after a change; RemoveAll is safe |
| Go | native | a range over a map defines what happens on a change; a range over a slice evaluates it once |
| Rust | native | the borrow checker rejects a change to a collection while a loop borrows it; retain is safe |
| C | absent | no iterators in the language; a pointer into a buffer dangles after realloc |
| C++ | native | each container lists which changes invalidate iterators; the use of an invalid iterator is undefined behavior |
| Bash | n/a | for x in "${a[@]}" expands the array once, before the loop starts |
| PowerShell | native | foreach over a list that changes fails with an error that the collection was modified |
| SQL | n/a | no iterators; an UPDATE or DELETE works on a set of rows |
| Regex | n/a | no collections |
| HTML | n/a | no collections |
| CSS | n/a | no collections |
The languages pick one of four answers. Java, C#, Python dictionaries and PowerShell detect the change and throw an error. JavaScript and Go define the result, so the loop goes on with rules that a reader must know. C++ leaves the result undefined and documents which operations are safe. Rust rejects the program before it runs.
The example files show these differences. Python removes from a list in place, over a copy and with a comprehension, and catches the error of a dictionary. JavaScript adds and removes elements in forEach and filters into a new array. Java catches a ConcurrentModificationException and removes with Iterator.remove and removeIf. C# catches an InvalidOperationException and uses RemoveAll. Go deletes map entries in a range loop and appends to a slice in one. Rust uses retain and collects the changes before it applies them. C keeps an index, not a pointer, across a realloc. C++ uses the iterator that erase returns and std::erase_if.
# A set also checks its size during a loop.
tags = {"a", "b", "c"}
try:
for t in tags:
tags.add(t.upper())
except RuntimeError as e:
print("RuntimeError:", e)
# Removing by index from the end moves only elements already passed.
nums = [1, 2, 2, 3, 4]
for i in range(len(nums) - 1, -1, -1):
if nums[i] % 2 == 0:
del nums[i]
print(nums)
# Two passes: collect the keys, then delete them.
stock = {"pen": 0, "ink": 5, "pad": 0}
empty = [k for k, v in stock.items() if v == 0]
for k in empty:
del stock[k]
print(stock)
# Changing values, not keys, is allowed.
prices = {"pen": 2, "ink": 5}
for k in prices:
prices[k] *= 10
print(prices)
RuntimeError: Set changed size during iteration
[1, 3]
{'ink': 5}
{'pen': 20, 'ink': 50}
- Verdict: native. A set raises the same
RuntimeErroras a dictionary when its size changes in a loop. A list has no check, so the code deletes by index from the end, where a deletion moves only the elements that the loop has already seen. The dictionary loop collects the keys first and deletes them in a second loop. An assignment to an existing key does not change the size, so the last loop is safe.
#include <list>
#include <print>
#include <vector>
int main() {
// erase returns the next valid iterator.
std::vector<int> v{1, 2, 2, 3, 4};
for (auto it = v.begin(); it != v.end();) {
if (*it % 2 == 0)
it = v.erase(it);
else
++it;
}
std::println("erase loop: {}", v.size());
// std::erase_if removes all matches in one call.
std::vector<int> w{1, 2, 2, 3, 4};
auto removed = std::erase_if(w, [](int x) { return x % 2 == 0; });
std::println("erase_if removed {}, left {}", removed, w.size());
// push_back past the capacity reallocates and invalidates all iterators.
std::vector<int> g;
g.reserve(2);
g.push_back(1);
g.push_back(2);
auto cap_before = g.capacity();
g.push_back(3);
std::println("capacity grew: {}", g.capacity() > cap_before);
// A list keeps iterators to the other elements valid.
std::list<int> l{1, 2, 3};
auto first = l.begin();
l.push_back(4);
l.erase(std::next(first));
std::println("list front still valid: {}", *first);
}
erase loop: 2
erase_if removed 3, left 2
capacity grew: true
list front still valid: 1
- Verdict: native.
v.erase(it)invalidatesit, so the loop takes the iterator thaterasereturns and steps only when it erases nothing.std::erase_ifreturns the number of removed elements. The thirdpush_backgrows the capacity, which reallocates the buffer and invalidates every iterator intog. Astd::listkeeps the iteratorfirstvalid through an insertion and through the erasure of another element.
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5));
try {
for (Integer n : nums) {
if (n % 2 == 0) nums.remove(n);
}
} catch (ConcurrentModificationException e) {
System.out.println("caught " + e.getClass().getSimpleName());
}
System.out.println("after the error: " + nums);
// The iterator's own remove keeps it valid.
nums = new ArrayList<>(List.of(1, 2, 3, 4, 5));
for (Iterator<Integer> it = nums.iterator(); it.hasNext(); ) {
if (it.next() % 2 == 0) it.remove();
}
System.out.println("Iterator.remove: " + nums);
// removeIf does the loop inside the list.
nums = new ArrayList<>(List.of(1, 2, 3, 4, 5));
nums.removeIf(n -> n % 2 == 0);
System.out.println("removeIf: " + nums);
// set is not a structural change, so it does not throw.
for (int i = 0; i < nums.size(); i++) nums.set(i, nums.get(i) * 10);
for (Integer n : nums) nums.set(0, n);
System.out.println("after set: " + nums);
}
}
caught ConcurrentModificationException
after the error: [1, 3, 4, 5]
Iterator.remove: [1, 3, 5]
removeIf: [1, 3, 5]
after set: [50, 30, 50]
- Verdict: native. The for-each loop removes 2, and the next call to
nextfinds that the list changed and throws, so 4 stays in the list.Iterator.removeremoves the element thatnextreturned and keeps the iterator valid.removeIfneeds no loop in user code.setchanges a value and not the structure, so the last loop does not throw: it writes each element into index 0, and the last one is 50.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t len = 3, cap = 3;
int *a = malloc(cap * sizeof *a);
if (a == NULL)
return 1;
for (size_t i = 0; i < len; i++)
a[i] = (int)(i + 1);
/* Keep an index, not a pointer: realloc can move the buffer. */
size_t n = len;
for (size_t i = 0; i < n; i++) {
if (len == cap) {
cap *= 2;
int *grown = realloc(a, cap * sizeof *a);
if (grown == NULL) {
free(a);
return 1;
}
a = grown;
}
a[len++] = a[i] * 10;
}
for (size_t i = 0; i < len; i++)
printf("%d%s", a[i], i + 1 < len ? " " : "\n");
/* Remove the even numbers in place with a read and a write index. */
size_t w = 0;
for (size_t r = 0; r < len; r++)
if (a[r] % 2 != 0)
a[w++] = a[r];
len = w;
printf("odd: %zu left, first %d\n", len, a[0]);
free(a);
return 0;
}
1 2 3 10 20 30
odd: 2 left, first 1
- Verdict: absent. C has no iterators, but a pointer into a buffer has the same problem: after
reallocmoves the buffer, an old pointer points to freed memory. The loop keeps the indexiand readsa[i]through the new pointer after each growth, and it saves the lengthnbefore the loop, so the appended elements do not add passes. The removal uses two indexes, one to read and one to write, in a single pass.
var nums = new List<int> { 1, 2, 3, 4, 5 };
try
{
foreach (var n in nums)
{
if (n % 2 == 0) nums.Remove(n);
}
}
catch (InvalidOperationException e)
{
Console.WriteLine($"caught {e.GetType().Name}");
}
Console.WriteLine($"after the error: {string.Join(",", nums)}");
// RemoveAll removes all matches in one call.
nums = new List<int> { 1, 2, 3, 4, 5 };
int removed = nums.RemoveAll(n => n % 2 == 0);
Console.WriteLine($"RemoveAll: {string.Join(",", nums)} ({removed} removed)");
// A for loop from the end does not use an enumerator.
nums = new List<int> { 1, 2, 2, 3, 4 };
for (int i = nums.Count - 1; i >= 0; i--)
{
if (nums[i] % 2 == 0) nums.RemoveAt(i);
}
Console.WriteLine($"backward: {string.Join(",", nums)}");
// A dictionary: loop over a copy of the keys.
var stock = new Dictionary<string, int> { ["pen"] = 0, ["ink"] = 5 };
foreach (var key in stock.Keys.ToList())
{
if (stock[key] == 0) stock.Remove(key);
}
Console.WriteLine($"stock: {string.Join(",", stock.Keys)}");
caught InvalidOperationException
after the error: 1,3,4,5
RemoveAll: 1,3,5 (2 removed)
backward: 1,3
stock: ink
- Verdict: native. The removal of 2 invalidates the enumerator of the list, and the next
MoveNextthrows anInvalidOperationException.RemoveAlldoes the loop inside the list and returns the count. Aforloop over the indexes from the end has no enumerator, so it can remove elements.ToList()copies the keys, so the loop can remove entries from the dictionary.
// forEach visits only the indexes below the first length.
const a = [1, 2, 3];
a.forEach((x) => {
if (x < 3) a.push(x * 10);
});
console.log(a);
// A removal shifts the elements, so the next one is skipped.
const b = [1, 2, 2, 3, 4];
const seen = [];
b.forEach((x, i) => {
seen.push(x);
if (x % 2 === 0) b.splice(i, 1);
});
console.log("seen:", seen.join(","), "left:", b.join(","));
// filter builds a new array and leaves the old one alone.
const c = [1, 2, 2, 3, 4];
console.log(c.filter((x) => x % 2 !== 0), c.length);
// A Map iterator sees entries added during the loop.
const m = new Map([["a", 1]]);
for (const [k, v] of m) {
if (v < 3) m.set(k + "+", v + 1);
}
console.log([...m.keys()].join(" "));
[ 1, 2, 3, 10, 20 ]
seen: 1,2,3,4 left: 1,2,3
[ 1, 3 ] 5
a a+ a++
- Verdict: native. JavaScript defines the result of each change, but the result is easy to get wrong.
forEachdoes not visit the two elements that it adds. Thespliceof the first 2 moves the second 2 to the index that the loop has passed, so the loop never sees it, and it stays in the array. AMapiterator visits entries in insertion order and sees the new entries, so the loop addsa+and thena++.
package main
import (
"fmt"
"slices"
"sort"
)
func main() {
// Deleting map entries during range is defined and safe.
stock := map[string]int{"pen": 0, "ink": 5, "pad": 0, "cap": 2}
for k, v := range stock {
if v == 0 {
delete(stock, k)
}
}
keys := make([]string, 0, len(stock))
for k := range stock {
keys = append(keys, k)
}
sort.Strings(keys)
fmt.Println(keys)
// The range expression is evaluated once, so append does not extend the loop.
s := []int{1, 2, 3}
passes := 0
for _, x := range s {
s = append(s, x*10)
passes++
}
fmt.Println(passes, s)
// slices.DeleteFunc removes all matches in one call.
nums := []int{1, 2, 2, 3, 4}
nums = slices.DeleteFunc(nums, func(n int) bool { return n%2 == 0 })
fmt.Println(nums)
}
[cap ink]
3 [1 2 3 10 20 30]
[1 3]
- Verdict: native. The Go specification defines a deletion during a
rangeover a map: an entry that is deleted before the loop reaches it is not produced. Therangeover the slice uses the slice that it evaluated at the start, so the three appends do not add passes.slices.DeleteFuncremoves the even numbers and returns the shorter slice.
use std::collections::HashMap;
fn main() {
let mut nums = vec![1, 2, 2, 3, 4];
// for n in &nums { if n % 2 == 0 { nums.remove(0); } }
// does not compile: error[E0502], nums is borrowed by the loop.
nums.retain(|n| n % 2 != 0);
println!("{:?}", nums);
// Changing the values in place is allowed with iter_mut.
for n in nums.iter_mut() {
*n *= 10;
}
println!("{:?}", nums);
// Collect the changes first, then apply them.
let mut stock: HashMap<&str, i32> = HashMap::from([("pen", 0), ("ink", 5), ("pad", 0)]);
let empty: Vec<&str> = stock.iter().filter(|(_, v)| **v == 0).map(|(k, _)| *k).collect();
for k in empty {
stock.remove(k);
}
let mut left: Vec<_> = stock.keys().collect();
left.sort();
println!("{:?}", left);
// An index loop that adds elements reads len() on each pass.
let mut v = vec![1, 2, 3];
let mut i = 0;
while i < v.len() && v.len() < 6 {
let x = v[i];
v.push(x * 10);
i += 1;
}
println!("{:?}", v);
}
[1, 3]
[10, 30]
["ink"]
[1, 2, 3, 10, 20, 30]
- Verdict: native. A
forloop over&numsborrows the vector, so a call toremoveorpushin the body is a compile error, not a run-time bug.retainremoves the elements in one call, anditer_mutchanges the values without changing the structure. For the map, the code collects the keys in one pass and removes them in a second. Awhileloop with an index copies each value out before it pushes, so it holds no borrow across the change.
Variations and related ideas
- Removal through the iterator. Java's
Iterator.removeand theeraseof C++, which returns the next valid iterator, change the collection in a way that the iterator follows. - Removal in one call.
removeIfin Java,RemoveAllin C#,retainin Rust andstd::erase_ifin C++ remove all the matching elements without a loop in user code. - Two passes. Collect the keys to remove in the first loop, then remove them in a second loop.
- A new collection. A filter or a comprehension builds a new collection and does not change the old one.
- Loops by index from the end. A loop that goes from the last index down to 0 can remove elements, because a removal moves only the elements that it has already passed.
- Snapshots. A copy-on-write collection gives the loop a snapshot, so changes do not affect it. See copy-on-write.
- Threads. When another thread changes the collection, the problem is a data race, and a fail-fast check does not fix it.
Pitfalls
- Errors that come late or not at all. Java's check is best-effort, so "it would be wrong to write a program that depended on this exception for its correctness"5. In Python, a list gives no error at all.
- References and pointers, not only iterators. In C++, a reference or a pointer to a vector element is invalidated by the same reallocation as an iterator3.
- The
end()iterator. A C++ loop that savesend()before the loop and inserts into a vector compares with an invalid iterator. cppreference notes that "std::vector::end is always invalidated"2 by a change. - Erase in a for loop. In C++,
for (auto it = v.begin(); it != v.end(); ++it) if (bad(*it)) v.erase(it);usesitafter the erase. Useit = v.erase(it)and step only when nothing was erased. - Changing a value is often allowed. Setting an element of an
ArrayListis "not a structural modification"4, so it does not throw. Changing a key of a hash table is different: it moves the entry.
Cost
A fail-fast check costs a counter in the collection and a comparison in each step of the iterator. Copying the collection before the loop costs memory and time in proportion to its size. A removal in one call, such as retain or removeIf, moves each element at most once, but a loop that removes elements one by one from an array list can take quadratic time. Java's ArrayList.remove "Shifts any subsequent elements to the left"4, so each removal moves all the elements after it.
References
- Storing Lists of Values with Vectors, The Rust Programming Language, Listing 8-6; Iterating Over the Values in a Vector
- Containers library, C++ reference, cppreference.com, Iterator invalidation
- std::vector::push_back, C++ reference, cppreference.com, Description
- ArrayList (Java SE 25 and JDK 25), Class description, fail-fast iterators; remove(int index)
- ConcurrentModificationException (Java SE 25 and JDK 25), Class description
- List<T>.GetEnumerator Method, .NET API reference, Remarks
- Built-in Types, The Python Standard Library, Dictionary view objects
- More Control Flow Tools, The Python Tutorial, 4.2 for Statements
- Array, MDN Web Docs, Mutating initial array in iterative methods
- The Go Programming Language Specification, For statements with range clause
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 | W2 basic |
|
Tag JEYEDG Edit this page History Report an error Markdown