Removing items from a list while iterating | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

6th Apr 2022, 3:25 AM
Sandeep
Sandeep - avatar
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. ...
6th Apr 2022, 3:44 AM
Simon Sauter
Simon Sauter - avatar
+ 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.
6th Apr 2022, 3:46 AM
Simon Sauter
Simon Sauter - avatar
+ 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.
7th Apr 2022, 12:09 PM
Erik
+ 2
If you absolutely want to you could do it like this: https://code.sololearn.com/czp1F18T3CCp/?ref=app
6th Apr 2022, 4:00 AM
Simon Sauter
Simon Sauter - avatar
+ 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))
6th Apr 2022, 7:28 PM
Brian
Brian - avatar