Python change a value of a variable by itself.

K

Kurda Yon

Hi,

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?

Thank you in advance.
 
S

Stephen Hansen

r_new[1] = r[1]

This is the problem. "r" is a dictionary, a set of key/object pairs in
essence. You're making the object that "r[1]" is pointing to a list, a
mutable sequence of items.

The expression "r[1]" will then return that list object and assign it
to "r_new[1]" -- but now both these two dictionaries are pointing to
the *same* object. Its not a copy of the object, but the same object
itself which you're storing in two different dictionaries.

If you want to store a copy of that list in r_new[1], you can use the
copy module, or something like:

r_new[1] = r[1][:]

which uses list slices to return a copy of the specified list.

HTH,

--Stephen
 
T

Tim Chase

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top