3

When iterating over a list and removing each item, why is every other item skipped and not removed? (I realise it may be bad practise to do this I just want to understand what is going on)

lst=[0,1,2,3,4,5,6,7,8,9]
for item in lst:
    lst.remove(item)
print(lst)

Expected output: [] Actual output: [1, 3, 5, 7, 9]

John Kugelman
  • 330,190
  • 66
  • 504
  • 555
amy
  • 137
  • 6
  • This answers it maybe: https://stackoverflow.com/a/1207427/9227188 – LeoE Nov 21 '19 at 12:10
  • If any answer does what you want (see @Tibbles's), please consider ticking it as correct. A reputation of 1 is enough to do it. I remind you this because newcomers often forget to do so. See [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) That being said, welcome on [SO](https://stackoverflow.com/). – keepAlive Nov 21 '19 at 12:16

2 Answers2

6

What happens here is the following:

You start with the following list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Then, in the first iteration of the for loop, you get the first item of the list which is 0, and remove it from the list. The updated list now looks like: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Then, at the second iteration of the loop, you get the second item in the updated list. Here, that second item is not 1 anymore but it is 2 (because you look at the updated list), so you remove 2 from the list. The updated list now looks like: [1, 3, 4, 5, 6, 7, 8, 9]

And it goes on... until you get: [1, 3, 5, 7, 9]

bglbrt
  • 1,913
  • 7
  • 21
2

To get the expected output, you need to iterate over a shallow copy of the list, while still removing items from the original list, as follows

lst=[0,1,2,3,4,5,6,7,8,9]
for item in lst[:]: # note the `[:]`
    lst.remove(item)
print(lst)
# returns []

otherwise, you are iterating over a list that changes simultaneously, cf @Tibbles's explanation.

keepAlive
  • 5,822
  • 5
  • 22
  • 37