We have the list (just for example):
nums = [0, 2, 1, 3, 2, 3, 0, 4, 2]
We have the simple code:
for i in nums:
if i == 2:
nums.remove(i)
print(nums)
And we have the output:
[0, 1, 3, 3, 0, 4]
Exellent. Now we change the list to:
nums = [0, 1, 3, 2, 2, 3, 0, 4, 2]
And the same code gives us the result:
[0, 1, 3, 3, 0, 4, 2]
Could anyone explain in simple words why two identical list values in a raw make this snippet work so… interesting? I mean, why last ‘2’? Why not removed?
>Solution :
Do not try to modify a list while iterating over it.
Rather create a new list with the elements you want. You can assign that new list to the same variable name.
>>> nums = [0, 2, 1, 3, 2, 3, 0, 4, 2]
>>> nums = [i for i in nums if i != 2]
>>> nums
[0, 1, 3, 3, 0, 4]
In your example, you have two consecutive values of 2: [0, 1, 3, 2, 2, 3, 0, 4, 2].
When your condition is met and you remove 2, the list is shortened. This means the value bound to i on the next loop iteration "skips" an element. We also know that remove will remove the first occurrence of that value.
If we look at the progression, it might look something like the following, with three occurrences of 2 but only two removals:
[0, 1, 3, 2, 2, 3, 0, 4, 2]
^
[0, 1, 3, 2, 2, 3, 0, 4, 2]
^
[0, 1, 3, 2, 2, 3, 0, 4, 2]
^
[0, 1, 3, 2, 2, 3, 0, 4, 2]
^
[0, 1, 3, 2, 3, 0, 4, 2]
^
[0, 1, 3, 2, 3, 0, 4, 2]
^
[0, 1, 3, 2, 3, 0, 4, 2]
^
[0, 1, 3, 2, 3, 0, 4, 2]
^
[0, 1, 3, 3, 0, 4, 2]
Using the new list approach with this initial list we see the expected result:
>>> nums = [0, 1, 3, 2, 2, 3, 0, 4, 2]
>>> nums = [i for i in nums if i != 2]
>>> nums
[0, 1, 3, 3, 0, 4]