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
  • 349,597
  • 67
  • 533
  • 578
amy
  • 354
  • 1
  • 9

2 Answers2

7

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
  • 2,018
  • 8
  • 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
  • 6,369
  • 5
  • 24
  • 39