Bug with lists of pairs of lists and append()

Paul Hankin paul.hankin at gmail.com
Fri Sep 28 19:09:34 EDT 2007


On Sep 28, 11:25 pm, Gabriel Zachmann <z... at REMOVEME.in.tu-
clausthal.de> wrote:
> could some kind soul please explain to me why the following trivial code is
> misbehaving?
>
> 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

What TeroV said - you need to copy the lists into s otherwise they'll
still mutate when you pop or append to them.
Try putting an extra "print s" after the s.append(x) line, and you'll
find that s changes between there and the final print statement
outside the loop.

Here's code that works:
s, l, r = [], [0], [1, 2]
while r:
    x = (list(l), list(r))
    print x
    s.append(x)
    l.append(r.pop(0))
print s

I'm using list(l) to copy the list, Tero uses l[:], but the idea is
the same.

But do you just want all proper partitions of lst? Then this is much
simpler:
lst = [0, 1, 2]
s = [(lst[:i], lst[i:]) for i in range(1, len(lst))]

--
Paul Hankin




More information about the Python-list mailing list