A few things to remember here:
- When you use the code
for i in nums:
the i is the actual value not the index
- .remove(i) is going to remove by value, which is fine
- .remove(i) will remove only the first instance
The problem you are running into is because you're iterating the list and removing items at the same time. There are many ways to work around this, but a really simple method to get this working is effectively making a copy of the list in the iteration.
You can do this by changing your iteration to
for i in list(nums):
and your final outcome will be the [0, 1, 3, 0, 4] that you're expecting.
Also note that in the original code, when you think it's found and is removing the final 2, it's actually removing the second 2 which is why you are left with the 2 at the end.
Hopefully that helps to clarify things a bit