Bug with lists of pairs of lists and append()

Gabriel Zachmann zach at REMOVEME.in.tu-clausthal.de
Fri Sep 28 18:25:42 EDT 2007


Well,

could some kind soul please explain to me why the following trivial code is
misbehaving?

#!/usr/bin/python

lst = [ 0, 1, 2 ]

s = []

l = [ lst[0] ]
r = lst[1:]
while r:
    x = (l,r)
    print x
    s.append( x )

    l.append( r.pop(0) )

print s



The output I get is:

([0], [1, 2])
([0, 1], [2])
[([0, 1, 2], []), ([0, 1, 2], [])]

and the error is in the last line: the two pairs in the outer list are
identical and they should be as the pairs on the first and the 2nd line,
respectively!

I think I'm going nuts -- for the life of me I don't see what's going on ...
(I've been tracking down a bug in my larger python script, and the cause
seems to boil down to the above snippet.)

Thanks a lot in advance for any insights, etc.

Best regards,
Gabriel.




More information about the Python-list mailing list