[Tutor] python dictionaries (copy by reference or copy by value?)
Steven D'Aprano
steve at pearwood.info
Sun May 3 04:32:15 CEST 2015
On Sat, May 02, 2015 at 04:25:41PM -0700, Alex McFerron wrote:
> trying to understand why this is true
[...]
> question: if y=x from step 2 (the copy job) is just creating a pointer y
> that points to the same thing as x then why when i set x = {} in step 5
> does that also not cause y to equal {}?
>
> what am i not understanding about python dictionaries?
Python, like most modern languages, is neither copy-by-value nor
copy-by-reference.
Python uses *exactly* the same name-binding mechanism for all values,
regardless of type, and all names, whether they are global variables,
function parameters, or anything else.
I discuss this question as it applies to function arguments here:
http://import-that.dreamwidth.org/1130.html
but the same reasoning applies to any other assignment. The important
thing to remember is that
y = x
doesn't make a copy of x, it just makes y refer to the same object as x
currently refers to. This is *not the same* as making y refer to x
(that is, y and x are permanently linked to be alternative names for
the same variable). Can you see the difference? If not, I'm happy to
respond with more detail.
--
Steve
More information about the Tutor
mailing list