Safe Python List Iteration and Filtering
Core idea
When iterating over a list, removing an item shifts later positions. The next iteration may skip an item that has shifted into a position already visited. Prefer building a new list of the items you want to keep. If you must remove items from the original, loop over a shallow copy and change the original instead.
readings = [0, 7, -1, 4]valid = []for value in readings: if value > 0: valid.append(value)print(valid)print(readings)The result keeps positive values in order, and the original stays unchanged.
Remove from the original safely
items = [0, 0, 5]for item in items.copy(): if item == 0: items.remove(item)print(items)The loop visits both zeros in the copy, so both are removed from the original.
Incorrect removal: demonstration
items = [0, 0, 5]for item in items: if item == 0: items.remove(item)print(items)The first zero disappears, shifting the second zero to index 0. Iteration advances to index 1 and skips that zero. This example is intentionally incorrect for filtering.
Common mistake
Do not assume remove during traversal will visit each original item. Avoid appending to the same list during traversal as well, because the loop may visit added items and fail to terminate.
Practice
Mini-project: from [3, -1, -2, 0, 7, 3], keep nonnegative readings in a new list and then sort that list. Check the original remains unchanged.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Safe list filtering
Check your understanding of list iteration safety.
What is printed?
items = [0, 0, 5]for item in items: if item == 0: items.remove(item)print(items)What is printed?
result = []for item in [2, 0, 4]: if item > 0: result.append(item)print(result)What is printed?
items = [0, 0, 3]for item in items.copy(): if item == 0: items.remove(item)print(items)Which approach keeps the source list unchanged while filtering?