Remove Item From List While Iterating

Jan 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:        items.remove(_item)

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]

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.