One day when I was writing python code, something strange happened ...
x = [1, 2, 3, 4, 5]
for i in x:
x.remove(i)
print(x)
>>>
[2, 3, 4, 5] #Recognize
[2, 4, 5] # ???If you pull out 1 and 2[3, 4, 5]Then!?!?
[2, 4] # ???????
By the way, it was the same when I tried it with ruby.
x = [1, 2, 3, 4, 5]
for i in x do
x.delete(i)
print(x)
end
>>>
[2, 3, 4, 5][2, 4, 5][2, 4] => [2, 4]
Hi, "for i in x" means
It seems that it is trying to refer to the 0, 1, 2, ..., nth of x every time the loop is looped.
It is good to copy the list with [:] or copy ()
x = [1, 2, 3, 4, 5]
for i in x[:]:
x.remove(i)
print(x)
>>>
[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]
from copy import copy
x = [1, 2, 3, 4, 5]
for i in copy(x):
x.remove(i)
print(x)
>>>
[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]
I was worried about 30 minutes, "Hmm, hmm ...". If you press it with numpy, you will be confused by the destructive methods of the standard list ...
Recommended Posts