Bug with lists of pairs of lists and append()

G

Gabriel Zachmann

Well,

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


#!/usr/bin/python
s = []
l = [ 0 ]
r = [0, 0]
while r:
x = (l,r)
print x
s.append( x )
l.append( r.pop(0) )
print s



The output I get is:

([0], [0, 0])
([0, 0], [0])
[([0, 0, 0], []), ([0, 0, 0], [])]

and the error is in the last line: the two pairs in the outer list are
identical and they should be equal to the pairs one the first and the
2nd line, respectively! Shouldn't they?

I think I'm going nuts -- for the life of me I don't see what's going on ...

Thanks a lot in advance for any insights, etc.

Best regards,
Gabriel.
 
T

TeroV

Gabriel said:
Well,

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


#!/usr/bin/python
s = []
l = [ 0 ]
r = [0, 0]
while r:
x = (l,r)
print x
s.append( x )
l.append( r.pop(0) )
print s



The output I get is:

([0], [0, 0])
([0, 0], [0])
[([0, 0, 0], []), ([0, 0, 0], [])]

and the error is in the last line: the two pairs in the outer list are
identical and they should be equal to the pairs one the first and the
2nd line, respectively! Shouldn't they?

I think I'm going nuts -- for the life of me I don't see what's going on
...

Thanks a lot in advance for any insights, etc.

Best regards,
Gabriel.

You didn't say what it is supposed to do.
But, does replacing line "x = (l, r)" with "x = l[:], r[:]" do the trick?

In the original code you do basically the same as this
>>> a = []
>>> b = [1,2]
>>> a.append(b)
>>> b.append(3)
>>> a
[[1, 2, 3]]

HTH :)
 
G

Gabriel Zachmann

Thanks a lot for your response, too.
Best regards,
Gabriel.

--
______________________________________________________________
Life is so constructed that the event does not, cannot,
will not match the expectation. (Charlotte Bronte)
______________________________________________________________
zach in.tu-clausthal.de __@/' www.gabrielzachmann.org
______________________________________________________________
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top