-3
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]?

DatascienceGeeks
  • 368
  • 2
  • 12
  • Have you tried to step through with a debugger? Or write out what is happening. – Brian S Dec 11 '17 at 12:59
  • 2
    This _should_ be _more than_ confusing. It's a good thing. Stay away from modifying the collection while iterating. – xtofl Dec 11 '17 at 13:00

1 Answers1

0

You can't modify the collection you are iterating on. This will do the trick:

for element in lst[:] : lst.remove(element)