1

I'm very confused. When I run the following code I assume the list, l, ends empty but always ends with one remaining item, i.e.:

l = [1,2,3]
for item in l: 
    l.remove(item)
    
print(l) 

the result is [2]

but if I re-run the same loop again the list is finally emptied

for item in l: 
    l.remove(item)
    
print(l)

the result is []

Sure there is something I'm doing wrong but for now what I'm getting is very annoying.

I apreciate if somebody can explains me what's going on.

Thanks

Ernesto
  • 19
  • 2
  • 1
    It is because you are removing items while you are iterating over the list itself. So if you remove the item and then move forward by one, you skip 2 and that is why it is left over in the first loop. l=[1,2,3] originally, after first iteration l=[2,3], but now you have moved to index 1, which is 3 instead of 2. – Richard K Yu Feb 01 '22 at 04:01

1 Answers1

1

There’s a simple fix, just do this

l = [1,2,3]
for item in list(l): 
    l.remove(item)
    
print(l) 

The reason your method doesn’t work is that you are iterating over the list while removing items on the list. However, if you use the list method on l, you are passing a temporary copy of the list into the for loop and iterating over that. The Length will remain constant while you remove the items.

anarchy
  • 3,709
  • 2
  • 16
  • 48