iterating lists

Alf P. Steinbach alfps at start.no
Sat Jan 23 10:45:30 EST 2010


* ceciliaseidel at gmx.de:
> 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:
>    print(l1.pop())  #prints only "go steady" - why not "ready"??
> 
> for w in range(len(l2)):
>    print(l2.pop())  #prints "three two one" as expected
>   for w in l3:
>    print(l3.pop()) #prints "lift off" - inconsistent to first case...
> 
> 
> At least for 2.2.3 I found the first way to iterate the list as default, 
> I guess it is deprecated now but still what happens seems weird to me...

Arnaud Delobelle has already answered your question, but you might alternatively 
try this angle:


l1 = ["ready", "steady", "go"]
l2 = ["one", "two", "tree"]
l3 = ["lift off"]

for w in l1:
    print( w, l1 )
    print(l1.pop())  #prints only "go steady" - why not "ready"??

for w in range(len(l2)):
    print(l2.pop())  #prints "three two one" as expected
for w in l3:
    print( w, l3 )
    print(l3.pop()) #prints "lift off" - inconsistent to first case...


If the list has at least one item you always get into the first iteration of the 
loop. I.e. there's no inconsistency, unless you count the lack of an exception 
as an inconsistency. I don't know whether the behavior is clearly defined or 
not; there is a possibility that it might be well-defined.


Cheers & hth.,

- Alf



More information about the Python-list mailing list