+ 2
Removing items from a list while iterating
mylist = [i for i in range(8)] for i in mylist: print(f'Index: {i} List: {mylist}') mylist.remove(i) print(mylist) print(sum(mylist)) #Output: > [1,3,5,7] >16 This code is take from here: https://code.sololearn.com/cACGawItXq1i/?ref=app mylist should be empty but the code outputs odd numbers?
6 Answers
+ 5
When you remove an item from a list the index of all following items is reduced by one. But the loop goes on to the next index.
So in the first iteration you delete the value at index 0: 0. Because of this 1 moves to index 0, 2 to index 1, etc. In the second iteration you remove the value at index 1, which is now 2. ...
+ 5
In general modifying a list (or other container) while iterating over it is very error prone and should therefore be avoided unless absolutely necessary.
+ 4
For the general issue of removing a large number of specific items throughout a big list, a better approach (faster but using more memory) would be to construct a new list, containing (appending) only the items from the first list that you want to keep. This avoids nasty surprises from trying to iterate over a list with contents that are changing -- and also avoids the use of list.remove() over and over, which is expensive (slow) because the list is being re-indexed repeatedly.
+ 2
If you absolutely want to you could do it like this:
https://code.sololearn.com/czp1F18T3CCp/?ref=app
+ 2
You can work around the problem by iterating backward from the end of the list, though only if the items are unique.
mylist = [i for i in range(8)]
for i in mylist[::-1]:
print(f'Index: {i} List: {mylist}')
mylist.remove(i)
print(sum(mylist))