Let it
be an iterable element in python.
In what cases is a change of it
inside a loop over it
reflected? Or more straightforward: When does something like this work?
it = range(6)
for i in it:
it.remove(i+1)
print i
Leads to 0,2,4 being printed (showing the loop runs 3 times).
On the other hand does
it = range(6)
for i in it:
it = it[:-2]
print it
lead to the output:
[0,1,2,3]
[0,1]
[]
[]
[]
[],
showing the loop runs 6 times. I guess it has something to do with in-place operations or variable scope but cannot wrap my head around it 100% sure.
Clearification:
One example, that doesn't work:
it = range(6)
for i in it:
it = it.remove(i+1)
print it
leads to 'None' being printed and an Error (NoneType has no attribute 'remove') to be thrown.