pythonpython-3.xlistforeach

Why does removing items from list while iterating over it skip every other item


When iterating over a list and removing each item, why is every other item skipped and not removed? (I realise it may be bad practice 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]


Solution

  • 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]