I was trying out some things with lists in the interactive interpreter and I noticed this:
>>> list = range(1, 11)
>>> for i in list:
... list.remove(i)
...
>>> list
[2, 4, 6, 8, 10]
Can anyone explain why it left even numbers? This is confusing me right now... Thanks a lot.
It isn't safe to modify a list that you are iterating over.
My guess is that the for loop is implemented like the following:
list = range(1, 11)
i = 0
while i < len(list):
list.remove(list[i])
i += 1
print(list)
Every time an element is removed, the "next" element slides into its spot, but i
gets incremented anyway, skipping 2 elements.
But yes, ObscureRobot is right, it's not really safe to do this (and this is probably undefined behavior).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With