SoftwareSideHustles
Debugging

Removing Items While Iterating — "dictionary changed size during iteration", ConcurrentModificationException and Skipped Elements

Why removing from a list while looping skips elements, why Python raises "dictionary changed size during iteration" and Java throws ConcurrentModificationException — and the correct pattern in each language.

By Software Side Hustles Editorial Team · Published · Updated · 5 min read

Quick answer: do not add or remove items from a collection while a loop is walking over it. Build a new collection instead ([x for x in items if keep(x)], items.filter(keep), list.removeIf(...)), or iterate over a copy (for k in list(d):). In Java, remove through the iterator with iterator.remove() or use removeIf.

The three symptoms of the same bug

LanguageWhat happens
Python listSilently skips elements — no error
Python dict / setRuntimeError: dictionary changed size during iteration / Set changed size during iteration
Java collectionsjava.util.ConcurrentModificationException (usually)
C# collectionsInvalidOperationException: Collection was modified; enumeration operation may not execute.
JavaScript array with spliceSilently skips elements

The silent versions are the dangerous ones.

Why removing from a list skips elements

python
nums = [1, 2, 2, 3]
for n in nums:
if n == 2:
nums.remove(n)
print(nums) # [1, 2, 3] — one 2 survived

The loop tracks a position. When it is at index 1 and removes that element, everything shifts left by one, so the second 2 moves into index 1. The loop then advances to index 2 — and never looks at it. Your tests pass whenever matching items are never adjacent.

How to remove items from a list in Python

python
nums = [n for n in nums if n != 2] # build a new list — clearest
nums[:] = [n for n in nums if n != 2] # same, but mutates the original object in place
for n in nums.copy(): # or iterate a copy
if n == 2:
nums.remove(n) # still O(n) per removal

The comprehension is both the clearest and the fastest: one pass, O(n). Removing elements one by one with list.remove is O(n) each, so O(n²) overall. Use nums[:] = ... when other code holds a reference to the same list and should see the change.

If you must use indexes, walk backwards, so removals only shift elements you have already visited:

python
for i in range(len(nums) - 1, -1, -1):
if nums[i] == 2:
del nums[i]

How to fix "dictionary changed size during iteration"

python
prices = {"apple": 0, "pear": 3, "plum": 0}
for k in prices:
if prices[k] == 0:
del prices[k]
# RuntimeError: dictionary changed size during iteration

Iterate over a snapshot of the keys, or build a new dictionary:

python
for k in list(prices): # list() copies the keys first
if prices[k] == 0:
del prices[k]
prices = {k: v for k, v in prices.items() if v != 0} # usually nicer

Changing the values of existing keys during iteration is fine; only adding or removing keys is not. The same rules apply to sets.

How to fix ConcurrentModificationException in Java

java
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4));
for (Integer n : nums) {
if (n == 1) nums.remove(n); // ConcurrentModificationException
}

The enhanced for uses an iterator, and ArrayList's iterator detects that the list changed underneath it. Correct options:

java
nums.removeIf(n -> n == 1); // simplest, Java 8+
Iterator<Integer> it = nums.iterator();
while (it.hasNext()) {
if (it.next() == 1) it.remove(); // remove through the iterator
}
List<Integer> kept = nums.stream().filter(n -> n != 1).toList(); // new list

For maps: map.entrySet().removeIf(e -> e.getValue() == 0) or map.values().removeIf(v -> v == 0).

Why it sometimes does not throw

Removing the second-to-last element in a for-each loop does not throw — the loop simply ends early and skips the last element:

java
List<Integer> l = new ArrayList<>(List.of(1, 2, 3, 4));
for (Integer x : l) if (x == 3) l.remove(x);
// no exception — and 4 was never checked

After the removal the list has three elements, the iterator's cursor is already at 3, and hasNext() returns false. That is why the exception is described as "best effort": you cannot rely on it to catch the bug.

Also note: despite the name, ConcurrentModificationException usually has nothing to do with threads. When multiple threads do modify a collection, use concurrent collections such as ConcurrentHashMap or CopyOnWriteArrayList, or synchronise access.

JavaScript: splice in a loop

javascript
const a = [1, 2, 2, 3];
for (let i = 0; i < a.length; i++) {
if (a[i] === 2) a.splice(i, 1); // skips the second 2
}

Use filter to build a new array, loop backwards, or decrement i after splicing:

javascript
const kept = a.filter((x) => x !== 2);
for (let i = a.length - 1; i >= 0; i--) if (a[i] === 2) a.splice(i, 1);

JavaScript Map and Set are an exception: deleting entries during iteration is well defined and safe. Go maps also allow delete inside a range loop.

C#

csharp
list.RemoveAll(x => x == 2); // List<T>
foreach (var key in dict.Keys.ToList()) // copy keys first
if (dict[key] == 0) dict.Remove(key);

On .NET Core 3.0 and later, Dictionary.Remove during a foreach over the same dictionary is permitted, but older frameworks throw, and other collections still do — copying keys keeps the code portable.

Adding items while iterating

Appending to a list you are looping over can create an infinite loop in Python and JavaScript, because the loop keeps finding new elements. If you are processing a work queue that grows — a crawler, a graph traversal — use an explicit queue (collections.deque) with a while queue: loop, which makes the growth intentional.

Frequently asked questions

Why doesn't Python raise an error for lists like it does for dicts?

Lists are iterated by index, which keeps working after a change; dictionaries track their size during iteration and detect changes to protect their internal hash table.

Is iterating over a copy expensive?

It costs O(n) memory and time, which is usually negligible compared with the bug it prevents. Building a filtered result is the same cost and often clearer.

How do I modify items, not remove them?

Assign by index (for i, x in enumerate(items): items[i] = x * 2) or build a new list with a comprehension. Rebinding the loop variable (x = x * 2) does not change the list.

Where this skill pays off

A loop that "works" but silently skips adjacent matches is a textbook example of code that passes a quick test and fails in production. Our free average rating exercise is built on a similar skipped-element bug. Finding these is everyday work in AI code evaluation — see how to evaluate AI-generated code.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy