possible python bug here

Tuure Laurinolli tuure at laurinolli.net
Mon Aug 30 00:17:58 CEST 2004


manuel wrote:

> 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.



More information about the Python-list mailing list