unexpected behavior: did i create a pointer?

Dustan DustanGroups at gmail.com
Fri Sep 7 13:47:12 CEST 2007


On Sep 7, 3:07 am, gu <pistacc... at gmail.com> wrote:
> hi to all!

Hi!

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

Welcome to Python! You might want to look at the documentation:
http://docs.python.org/

And the tutorials:
http://docs.python.org/tut/tut.html

Leaping into python from another language without looking at the above
documentation is not wise, since python has both a very different
structure and a somewhat different philosophy from other languages.




More information about the Python-list mailing list