Reputation: 9
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
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