Bug with lists of pairs of lists and append()

Jason M Barnes json.barnes at gmail.com
Fri Sep 28 19:29:54 EDT 2007


On 9/28/07, Gabriel Zachmann <zach at removeme.in.tu-clausthal.de> wrote:
> 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.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

If you're familiar with C or C++, think of s as holding a pointer to x
which in turn holds a pointer to l and r, so when you change l or r, x
(and s indirectly) is still pointing to the same lists which by the
end of your loop have changed to r=[] and l=[0,1,2].

BTW:  It's not really "misbehaving."  It's doing exactly what you're
telling it to do ;-)

Jason



More information about the Python-list mailing list