Remove Item From List While Iterating

January 16, 2018
Interate copy of list using items[:]

Since modiying the list while iterating will mutate the list, you can iterate copy of the list instead.

items = [1, 2, 3, 4]

for _item in items[:]:
    if _item <= 2:

Alternatively, you can create a new list after filtering.

items = [_item for _item in items if _item <= 2]

If you want to mutate the existing list (it might be reference else where) rather than creating new list.

items[:] = [_item for _item in items if _item <= 2]
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.