a = [1, 2, 3, 4, 5]
for i in a:
a.remove(i)
print(a)
results : [2, 4]
I read a post about modifying list while iterating, and then I tried the code above, the result seems a little confusing.
Why the results here is [2, 4]?
a = [1, 2, 3, 4, 5]
for i in a:
a.remove(i)
print(a)
results : [2, 4]
I read a post about modifying list while iterating, and then I tried the code above, the result seems a little confusing.
Why the results here is [2, 4]?
You can't modify the collection you are iterating on. This will do the trick:
for element in lst[:] : lst.remove(element)