Sub topic 13
Why You Should Not Modify a List While Looping Over It
This chapter assumes you can write a basic for loop, know that list.remove() and list.append() change a list in place, and have read the earlier chapters on the for statement and the iterator protocol. Here you will see why changing a list during iteration gives wrong results without raising an error. You will also learn the safe patterns that replace it.
The surprise
Suppose you want to delete every even number from a list. This looks reasonable:
nums = [2, 4, 6, 8]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # [4, 8], not []Python raises no error, and the loop finishes normally. The result is wrong, and the code gives no sign of it. Bugs like this are easy to miss in tests.
What the loop is really doing
A for loop over a list does not remember the items it has already seen. The list iterator keeps one piece of state, an integer position. Each step does roughly this:
- If the position is at or past the current length of the list, stop.
- Otherwise, return
nums[position]and add 1 to the position.
The iterator reads the list as it is at that moment, so any change you make shifts the items under the position. You can watch it happen by printing the position and the list:
nums = [2, 4, 6, 8]
for i, n in enumerate(nums):
print("position", i, "sees", n, "list is", nums)
if n % 2 == 0:
nums.remove(n)
print(nums)The output is:
position 0 sees 2 list is [2, 4, 6, 8]
position 1 sees 6 list is [4, 6, 8]
[4, 8]At position 0 the loop sees 2 and removes it. Every later item moves one slot to the left, so 4 is now at position 0. The iterator moves on to position 1 and finds 6. The 4 is never examined. After 6 is removed the list has two items, position 2 is past the end, and the loop stops. The 8 is never examined either.
Removal is the common case, but the same mechanism affects other changes.
Other kinds of modification
Each change to the list's structure has its own failure mode:
| Change during the loop | What happens |
|---|---|
| `remove()`, `pop()` or `del` | Later items shift left, so some are skipped, and the loop ends early. |
| `insert()` at an earlier position | Later items shift right, so the current item can be seen again. |
| `append()` | The loop sees the new items too, and can run forever if you keep appending. |
| Changing `nums[i]` to a new value | Safe. The length and positions do not change. |
Appending is easy to demonstrate with a guard so the loop ends:
items = [1]
for x in items:
if len(items) < 5:
items.append(x + 1)
print(items) # [1, 2, 3, 4, 5]The loop visits items it just added. Without the len(items) < 5 check, this loop would never finish. Sometimes growing a list while walking it is deliberate, for example in a work queue. In that case, prefer a while loop that states the stopping rule openly.
Dictionaries and sets behave differently
Dictionaries and sets do not use a position. They detect a change in size and refuse to continue:
ages = {"ann": 31, "bob": 17, "cy": 45}
try:
for name, age in ages.items():
if age < 18:
del ages[name]
except RuntimeError as err:
print(err) # dictionary changed size during iterationThis check is more helpful than silent skipping, but it is not a complete safeguard. It compares sizes, so a loop that deletes one key and adds another between steps can go undetected. Treat any structural change to a dict or set during iteration as a bug.
Safe patterns
Build a new list
The simplest fix is to describe what you want to keep. A list comprehension (covered in a later chapter) does this in one line:
nums = [2, 4, 6, 8, 9]
nums = [n for n in nums if n % 2 != 0]
print(nums) # [9]The same idea works with an ordinary loop that appends to a second list:
nums = [2, 4, 6, 8, 9]
kept = []
for n in nums:
if n % 2 != 0:
kept.append(n)
print(kept) # [9]Update the list in place with slice assignment
Rebinding the name nums creates a new list. Other names that point to the old list do not see the change. If the list is shared, for example it was passed in as an argument, assign to the whole slice instead:
nums = [1, 2, 3, 4, 5, 6]
alias = nums
nums[:] = [n for n in nums if n % 2]
print(alias) # [1, 3, 5]The comprehension on the right builds a new list first. Then nums[:] = ... replaces the contents of the original list object.
Loop over a copy
If you need to call remove() or similar, iterate over a snapshot and modify the original:
nums = [2, 4, 6, 8, 9]
for n in nums[:]: # nums[:] and list(nums) both make a shallow copy
if n % 2 == 0:
nums.remove(n)
print(nums) # [9]The copy is never changed, so the iterator's position stays valid. This costs extra memory, and each remove() searches the list from the start, which makes the whole loop quadratic on large lists. Prefer the comprehension for big inputs.
For a dictionary, copy the keys:
ages = {"ann": 31, "bob": 17, "cy": 45}
for name in list(ages):
if ages[name] < 18:
del ages[name]
print(ages) # {'ann': 31, 'cy': 45}Walk backwards by index
When you must delete in place without a copy, go from the end. Removing an item only shifts items that you have already passed:
nums = [2, 4, 6, 8, 9]
for i in range(len(nums) - 1, -1, -1):
if nums[i] % 2 == 0:
del nums[i]
print(nums) # [9]Here range() is computed once from the starting length, which is safe because the loop only touches positions at or below the current index. Going forward the same way would fail with an IndexError once the list shrank.
What is safe
You may freely change the items of a list while looping, as long as the list's length and order stay the same:
prices = [10, 20, 30]
for i in range(len(prices)):
prices[i] = prices[i] * 2
print(prices) # [20, 40, 60]Rebinding the loop variable alone does nothing to the list. In for p in prices: p = p * 2, the list is unchanged because p is just a name. Mutating a mutable item, such as appending to an inner list, is also safe, because the outer list's structure does not change.
Choosing an approach
- Keeping a subset: use a comprehension. It is the shortest and clearest.
- A shared list that others hold a reference to: use slice assignment.
- Complex per-item logic with side effects: loop over a copy.
- Large lists where memory matters and order does not: go backwards by index.
- A queue that grows as you process it: use a
whileloop.
Exercise
Predict the output of this code, then explain why it is not the list of even numbers you might expect. nums = [1, 3, 4, 5, 6] for n in nums: if n % 2 == 1: nums.remove(n) print(nums) Then rewrite it so it removes all odd numbers correctly.
Show answer
It prints [3, 4, 6]. At position 0 the loop sees 1 and removes it, so the list becomes [3, 4, 5, 6]. The 3 slides into position 0, and the iterator moves to position 1, which holds 4. The 3 is skipped and stays in the list. At position 2 it sees 5 and removes it, giving [3, 4, 6]. Position 3 is past the end, so the loop stops. A correct version is nums = [n for n in nums if n % 2 == 0], which gives [4, 6]. Looping over a copy with for n in nums[:] also works.
Exercise
A function receives a list and must remove all negative numbers so that the caller's list is changed. Why does nums = [n for n in nums if n >= 0] inside the function not do this, and what single line fixes it?
Show answer
The assignment rebinds the local name nums to a new list. The caller's list object is untouched. Writing nums[:] = [n for n in nums if n >= 0] replaces the contents of the original list object, so the caller sees the change.