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 how lists and indexes work, and have seen range() and enumerate(). It explains one of the most common loop bugs: changing a list while a for loop is walking over it.
The bug
Suppose you want to remove every even number from a list. A direct approach looks reasonable:
nums = [2, 4, 6, 8]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # [4, 8], not [] as you might expectEvery number in the list is even, so you would expect an empty list. The result is [4, 8], and Python raises no error. The program is wrong and says nothing about it.
Why it happens
A for loop over a list does not take a snapshot of the list. It keeps an internal position, which is an index, and on each pass it reads the item at that position and then moves the position forward by one.
When you remove an item, every later item shifts one place to the left. The loop's position still moves forward, so it steps over the item that just moved into the current slot.
Here is the sequence for [2, 4, 6, 8]:
- Position 0 holds
2. It is even, so it is removed. The list is now[4, 6, 8]. - Position 1 holds
6. The4shifted into position 0 and was never visited.6is even, so it is removed. The list is now[4, 8]. - Position 2 is past the end of the list, so the loop stops.
The values 4 and 8 were skipped.
Adding items has a different failure mode. Appending to the list you are looping over can make the loop run for a very long time, or forever, because the end keeps moving away.
items = [1, 2, 3]
for x in items:
items.append(x) # never reaches the end; do not run thisThe fix: build a new list
The safest approach is to leave the original list alone while you loop, and to produce a new list that holds the items you want to keep.
nums = [2, 4, 6, 8]
kept = []
for n in nums:
if n % 2 != 0:
kept.append(n)
print(kept) # []A list comprehension does the same thing in one line:
nums = [2, 4, 6, 8]
nums = [n for n in nums if n % 2 != 0]
print(nums) # []If other code holds a reference to the same list and must see the change, assign into a slice instead. This replaces the contents in place without creating a new list object:
nums = [2, 4, 6, 8, 9]
nums[:] = [n for n in nums if n % 2 != 0]
print(nums) # [9]Other safe options
- Loop over a copy.
for n in nums[:]:orfor n in list(nums):iterates over a separate list, so removing fromnumsdoes not disturb the loop. This works but copies the whole list, andremove()still searches from the start each time. - Loop backwards by index. With
for i in range(len(nums) - 1, -1, -1):, deletingnums[i]only shifts items you have already visited. - Change values, not length. Assigning to an existing position, such as
nums[i] = nums[i] * 2insidefor i in range(len(nums)), is safe, because no item moves.
Exercises
Exercise
This code is meant to remove every word shorter than 4 letters. What does it leave in words, and why is that wrong? Rewrite it correctly.
words = ["a", "to", "tree", "it", "go", "leaf"]
for w in words:
if len(w) < 4:
words.remove(w)
Show answer
The loop skips items that shift left after a removal. It removes "a", then skips "to", removes "it", then skips "go", leaving ["to", "tree", "go", "leaf"]. A correct version is words = [w for w in words if len(w) >= 4], which gives ["tree", "leaf"].
Exercise
You loop over nums by index with for i in range(len(nums) - 1, -1, -1) and call del nums[i] for some items. Why does this avoid the skipping bug?
Show answer
Deleting nums[i] only shifts items at higher positions, and those have already been visited because the loop moves from the end toward the start. The positions still to be visited are unaffected.