[Tutor] python dictionaries (copy by reference or copy by value?)

Alan Gauld alan.gauld at btinternet.com
Sun May 3 02:01:59 CEST 2015


On 03/05/15 00:25, Alex McFerron wrote:

> step 1: x = {}
> step 2: y = x
> step 3: x['key'] = 'value'
> # at this point if i print x or y i see {'key', 'value'}
> step 4:  x['key'] = 'newValue' #and at this point printing x or y i see
> {'key', 'newValue'} and this is true if this was y['key']
>
> because of the behavior in step 4, i'm thinking, ok the copy job from step
> 2 was a pointer only and not a by value copy job. fair enough

First mistake is to think of step 2 as a "copy job" its not.
Python variables do not work like variables in C and other
similar languages. see below.

> step 5: x = {} #or y={}
> step 6: print both. and what i get here is that x will be empty but y will
> not (or visa verse)
>
> 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?

This has nothing to do with dictionaries. Try this:

 >>> a = 42
 >>> b = a
 >>> a = 66
 >>> print a,b   # => 66,42

The same behaviour.
Remember that unlike some other languages you may have used
variables are not bits of memory. They are labels that are
used as keys in a dictionary. Its a bit like sticking
a post-it note onto a physical object. Many notes can be
stuck to the same object. And you can take a note off an
object and stick it on a new one.

So in step 1 you  take a new post-it, write the name 'x'
on it and attach it to your dictionary.
Then in step 2 you do not copy anything, rather you get
another post-it and write the name 'y' on it, then you
stick it to the same dictionary object as x

In step 5 you move the first post-it, with 'x' on it, to a
new object. It just happens to be another dictionary, but
it could have been anything. But the post-it with 'y' on is
still stuck to the original dictionary object.

Does that help?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list