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

Alex McFerron pythonistaforhire at gmail.com
Sun May 3 01:25:41 CEST 2015


trying to understand why this is true

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

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?


More information about the Tutor mailing list