unexpected behavior: did i create a pointer?

neoedmund neoedmund at gmail.com
Mon Sep 10 05:30:04 EDT 2007


On Sep 7, 4:07 pm, gu <pistacc... at gmail.com> wrote:
> 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.

no language act like want you tought, or the assignment operation will
be too expensive.




More information about the Python-list mailing list