Deleting a List Item While Iterating
Let’s trim a long list and list the list.
Python 3.5
list_1 = [1, 2, 3, 4]list_2 = [1, 2, 3, 4]list_3 = [1, 2, 3, 4]list_4 = [1, 2, 3, 4]for idx, item in enumerate(list_1):del itemfor idx, item in enumerate(list_2):list_2.remove(item)for idx, item in enumerate(list_3[:]):list_3.remove(item)for idx, item in enumerate(list_4):list_4.pop(idx)print(list_1)print(list_2)print(list_3)print(list_4)
Can you guess why the output is [2, 4]
?
Explanation
- It’s never a good idea to change the object that you’re iterating over. The correct way to do so is to iterate over a copy of the object instead, and
list_3[:]
does just that.
Python 3.5
some_list = [1, 2, 3, 4]print(id(some_list))print(id(some_list[:])) # Notice that python creates new object for sliced list.
The difference between ...