Modifying While Looping
Concepts covered: List Modification
Why removing during a for loop skips items
A for loop over a list keeps a hidden position. It reads index 0, then 1, then 2, until the position passes the end. readings.remove(value) deletes the first item equal to value and shifts every later item 1 place left. The hidden position does not shift with them, so the item that slides into the current slot is never visited.
readings = [12, -1, -1, 7, -1, 9]
for value in readings:
print("checking", value)
if value == -1:
readings.remove(value)
print(readings)checking 12 checking -1 checking 7 checking -1 [12, 7, -1, 9]
| Position | Value read | Action | List afterwards |
|---|---|---|---|
| 0 | 12 | keep | [12, -1, -1, 7, -1, 9] |
| 1 | -1 | remove | [12, -1, 7, -1, 9] |
| 2 | 7 | keep | [12, -1, 7, -1, 9] |
| 3 | -1 | remove | [12, 7, -1, 9] |
| 4 | none | loop ends | [12, 7, -1, 9] |
The loop goes wrong in 2 ways. The skip hides the -1 that slid into position 1. The second remove then deletes the first -1 in the list, at index 1, which is a different -1 from the one the loop was reading at index 3. The loop never reads 9 at all. Nothing raises an error, so the job finishes and loads a -1 sentinel into the clean table.
3 safe ways to remove items
Build a new list
The clearest fix leaves the list being read untouched and appends each value worth keeping to a new list.
readings = [12, -1, -1, 7, -1, 9]
clean = []
for value in readings:
if value != -1:
clean.append(value)
print(clean)
print(readings)Output:
[12, 7, 9] [12, -1, -1, 7, -1, 9]
Every item is read exactly once, and the original survives for logging or a retry. The in-place options below are for when other code holds the same list and must see it shrink.
Loop over a copy
list(readings) builds a second list holding the same items. Loop over the copy and remove from the original. The copy never shifts, so every value is visited.
readings = [12, -1, -1, 7, -1, 9]
for value in list(readings):
if value == -1:
readings.remove(value)
print(readings)Walk backwards by index
del nums[i] deletes the item at index i and shifts only the items after it. A backward loop has already visited those items, so every index still ahead of it stays valid.
# Reverse iteration for safe deletion
nums = [1, 2, 3, 4, 5, 6, 7, 8]
for i in range(len(nums) - 1, -1, -1):
if nums[i] % 2 == 0:
del nums[i]
print("After removing evens:", nums)After removing evens: [1, 3, 5, 7]
range(len(nums) - 1, -1, -1) counts down from 7 to 0, since the stop of -1 is excluded. The program prints After removing evens: [1, 3, 5, 7].
Dicts refuse to change size
A dict checks its own size on every step of a loop over it. Deleting or adding a key mid-loop raises a RuntimeError at the next step. Replacing the value of an existing key is allowed, which is why the merge loop in the previous section worked. del retries[job] removes a key and its value.
retries = {"job_a": 0, "job_b": 3, "job_c": 1}
try:
for job, count in retries.items():
if count >= 3:
del retries[job]
except RuntimeError as error:
print("RuntimeError:", error)
print(retries)Output:
RuntimeError: dictionary changed size during iteration
{'job_a': 0, 'job_c': 1}The delete went through before the error, so the dict is changed and the loop stopped partway. That is a bad combination for a job that resumes. The fix is the copy again: for job, count in list(retries.items()): freezes the pairs into a list first, and the loop can then delete from the dict freely.
Appending is the one change that a for loop over a list keeps up with, because the hidden position reaches the new items. That makes for n in nums: nums.append(n) run until memory runs out. It also makes a work list possible on purpose. Processing an item appends the follow-up work it reveals, and the loop ends once nothing new is added.
What happens when this runs?
counts = [5, 0, 0, 3]
for i in range(len(counts)):
if counts[i] == 0:
del counts[i]
print(counts)- It prints [5, 3]: each zero is deleted when the loop reaches its index
- It prints [5, 0, 3]: the second zero shifts past the loop and survives
- It raises IndexError: range(4) was fixed up front and index 3 is gone
- It raises RuntimeError: a list cannot change size inside a loop over it
About this lesson
This section is part of the Loops: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.