Deleting a List Item While Iterating
We'll cover the following...
We'll cover the following...
Let’s trim a long list and list the list.
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.
The difference between del, remove, and pop:
del var_namejust removes the binding of thevar_namefrom the local or global namespace (that’s why thelist_1is unaffected).removeremoves the first matching value, not a specific index, and raisesValueErrorif the value is not found.popremoves the element at a specific index and returns it, and raisesIndexErrorif an invalid index is specified.
Why is the output [2, 4]?
- The list iteration is done index by index, and when we remove
1fromlist_2orlist_4, the contents of the lists are now[2, 3, 4]. The remaining elements are shifted down, i.e.,2is at index 0, and3is at index 1. Since the next iteration is going to look at index 1 (which is the3), the2gets skipped entirely. A similar thing will happen with every alternate element in the list sequence.