Ernesto
Ernesto

Reputation: 9

python, removing items from list

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

Upvotes: 0

Views: 48

Answers (1)

anarchy
anarchy

Reputation: 5184

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.

Upvotes: 0

Related Questions