Python change a value of a variable by itself.

Tim Chase python.list at tim.thechases.com
Tue Feb 17 11:29:57 EST 2009


> I have the following simple code:
> r = {}
> r[1] = [0.000000]
> r_new = {}
> print r[1][0]
> r_new[1] = r[1]
> r_new[1][0] = r[1][0] + 0.02
> print r[1][0]
> 
> It outputs:
> 0.0
> 0.02
> 
> it is something strange to me since in the first and second case I
> output the same variable (r[1][0]) and it the two cases it has
> different values (in spite on the fact, that between the 2 outputs I
> did not assign a new value to the variable).
> 
> Can anybody pleas explain me this strange behavior?

You're referencing into a single mutable object (a list):

   a = [1,2,3]
   b = a
   b[1] = 4
   print a

both r[1] and r_new[1] refer to the same list object, so when the 
contents of that single list object is changed ("r_new[1][0] = 
...") accessing it by either name ("r[1][0]" or "r_new[1][0]") 
returns the same list.

To create a new list in r_new, use

   r_new[1] = r[1][:]  # copy the contents of the list

-tkc








More information about the Python-list mailing list