possible python bug here

M

manuel

In the sample below, the foo function modify the b list,
but I think it should modify only c, not b! It work
correctly if if b is one dimension list instead two.

def foo(aList):
print "use foo..."
aList[2][0] += .35
aList[2][1] += .35
aList[2][2] += .35

p = [2.5,2.5,2.5]
b = [p,p,p,p]

c=b[:] #c is a totally new list cloned from b, it's not an alias!

print "b = ",b[2]

foo(c) #The argument is c, not b! Why b is modified too?

print "b = ", b[2]# after foo(c), the list b now is different!
 
P

Peter Kleiweg

manuel schreef:
In the sample below, the foo function modify the b list,
but I think it should modify only c, not b! It work
correctly if if b is one dimension list instead two.

def foo(aList):
print "use foo..."
aList[2][0] += .35
aList[2][1] += .35
aList[2][2] += .35

p = [2.5,2.5,2.5]
b = [p,p,p,p]

c=b[:] #c is a totally new list cloned from b, it's not an alias!

No it isn't. You didn't make a deep copy.
 
T

Tuure Laurinolli

manuel said:
In the sample below, the foo function modify the b list,
but I think it should modify only c, not b! It work
correctly if if b is one dimension list instead two.

def foo(aList):
print "use foo..."
aList[2][0] += .35
aList[2][1] += .35
aList[2][2] += .35

p = [2.5,2.5,2.5]
Here you bind the name p to a list.
b = [p,p,p,p]
Here you bind the name b to a list, which has four references to list p
c=b[:] #c is a totally new list cloned from b, it's not an alias!
Here you bind the name c to a list, which has four copies of the
references to list p
print "b = ",b[2]
Here you print the third reference to p of list b
foo(c) #The argument is c, not b! Why b is modified too?
Here you modify the third reference to p of list c
print "b = ", b[2]# after foo(c), the list b now is different!
Here you print the third reference to p of list b, it's still just
reference to list (originally bound to) p.

Note that also the other references to the changed list (b[0:4], c[0:4],
p) refer to the same changed list.
 

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
474,204
Messages
2,571,065
Members
47,672
Latest member
svaraho

Latest Threads

Top