Python change a value of a variable by itself.

Stephen Hansen apt.shansen at gmail.com
Tue Feb 17 11:28:14 EST 2009


On Tue, Feb 17, 2009 at 8:19 AM, Kurda Yon <kurdayon at yahoo.com> wrote:
> 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



More information about the Python-list mailing list