Content · Programming · Python

Python Lists: Remove Items Safely While Iterating

Removing elements from a list while iterating over that same list can skip items because indexes shift. A filtered copy or slice assignment is often clearer and safer. See two practical examples, edge cases and common.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

A queue should remove every completed task.

What You Need to Understand


Removing elements from a list while iterating over that same list can skip items because indexes shift. A filtered copy or slice assignment is often clearer and safer.

When to Use It


A queue should remove every completed task.

Step-by-Step Python Example


tasks = ["done", "done", "open", "done"]
tasks = [task for task in tasks if task != "done"]
print(tasks)

How the Example Works


The new list contains only open, avoiding index changes during iteration.

Example Output


['open']
[1, 3]

A Second Example


Compare this smaller variation with the main example, then experiment with your own values.

values = [1, 2, 3, 4]
values[:] = [value for value in values if value % 2]
print(values)

Important Behavior and Edge Cases


If other code holds a reference to the original list, reassignment will not update it. Use tasks[:] = [...] when you must preserve the original object.

Try It Yourself


Remove every even number from a list while keeping the same list identity.

Common Beginner Mistakes


  • If other code holds a reference to the original list, reassignment will not update it. Use tasks[:] = [...] when you must preserve the original object.
  • Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.

Key Takeaways


  • Removing elements from a list while iterating over that same list can skip items because indexes shift.
  • The new list contains only open, avoiding index changes during iteration.
  • If other code holds a reference to the original list, reassignment will not update it.
Share this resourceSend this page to someone who may find it useful.