iterating lists

ceciliaseidel at gmx.de ceciliaseidel at gmx.de
Sat Jan 23 11:29:06 EST 2010



Arnaud Delobelle schrieb:
> ceciliaseidel at gmx.de writes:
> 
>> As you were talking about list.pop()...
>>
>> Is anyone able to reproduce the following and explain why this happens
>> by chance? (Using 3.1.1)
>>
>> l1 = ["ready", "steady", "go"]
>> l2 = ["one", "two", "tree"]
>> l3 = ["lift off"]
>>
>> for w in l1:

Ouch... thanks Arnaud... The stable way would've been

for w in l1[:]: #use copy of l1 for iteration
	print(l1.pop()) #decomposite list

(just in case any other newbie is reading this...)


>>    print(l1.pop())  #prints only "go steady" - why not "ready"??
>>
> 
> I suggest you simulate the loop above using pen and paper, writing the
> value of w and the value of l1 at each iteration.  The behaviour you are
> observing should then be clearly explained.  And you should also realise
> that it's a really bad idea to mutate a list that you are iterating on!
> 
> HTH
> 




More information about the Python-list mailing list