I have this code in Python where I'm trying to remove all instances of the number 1 from a list. I also know that:
- It's not possible to mutate a list while iterating over it.
- remove() removes the first occurrence of an item which has multiple instances of it in the list.
my_list = [2, 3, 1, 5, 8, 4, 6, 1, 1]
print(my_list)
for num in my_list:
if num == 1:
my_list.remove(num)
print(my_list)
The output:
[2, 3, 1, 5, 8, 4, 6, 1, 1]
[2, 3, 5, 8, 4, 6, 1]
Considering the two points I mentioned, how is it that the list changes? And more importantly, why is the last 1 not removed from the list?