unexpected behavior: did i create a pointer?

gu pistacchio at gmail.com
Fri Sep 7 10:07:03 CEST 2007


hi to all!
after two days debugging my code, i've come to the point that the 
problem was caused by an unexpected behaviour of python. or by lack of 
some information about the program, of course! i've stripped down the 
code to reproduce the problem:

<code>
a = {}

for x in range(10):
     for y in range(10):
         a[x,y] = "0"

copyOfA = a

def functionA(x,y):
     print a[x,y],
     copyOfA[x,y] = "*"
     print a[x,y],copyOfA[x,y]


for x in range(10):
     for y in range(10):
         functionA(x,y)

</code>


now, in the second "for" cycle and in functionA() i only 'touch' copyOfA 
(altering it). as i don't touch the variable "a", i expect it not to be 
affected by any change, but copyOfA acts like a pointer to a and 
altering copyOfA's values result in altering the values of "a", so the 
result that i expect is:
0 0 *
0 0 *
0 0 *
0 0 *
[..]

but i get:
0 * *
0 * *
0 * *
0 * *
[..]

what's going on?
thanks in advance.



More information about the Python-list mailing list