[Tutor] updating a dictionary

Danny Yoo dyoo at hashcollision.org
Sat Feb 21 02:43:23 CET 2015


On Fri, Feb 20, 2015 at 3:47 PM, Chris Stinemetz
<chrisstinemetz at gmail.com> wrote:
>
> I understand what you are explaining to me but I am not sure why every
> instance of the key 8:value changes when I assign a new value to it.


Ah.  Be wary of structure sharing when the values being shared are mutable.


A textbook example of this would be:

###########################################
message = ['hello', 'world']
copy = message
copy.append('!')
print copy
print message
## What do we expect to see here?  What do we see?
###########################################

The code above here is wrong to use the word "copy" here, because it's
not copying the structure at all.  copy refers to the *same* list
value.  Mutations to the value will be observable when we access that
list through either 'message' or 'copy', since fundamentally they're
both referring to the same list value.

To copy a list, we can use a whole slice:

#####################
message = ['hello', 'world']
copy = message[:]
copy.append('!')
print copy
print message
#####################


I don't know what your program looks like at this point, so I can't
pinpoint exactly where this is happening, but at the very least, this
should help you figure out what's going on.

Feel free to ask if you'd like more explanation.  If you'd like a
visualization, also see:

http://pythontutor.com/visualize.html#code=message+%3D+%5B'hello',+'world'%5D%0Acopy+%3D+message%0Acopy.append('!')&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=2&rawInputLstJSON=%5B%5D&curInstr=0

and compare vs:

http://pythontutor.com/visualize.html#code=message+%3D+%5B'hello',+'world'%5D%0Acopy+%3D+message%5B%3A%5D%0Acopy.append('!')&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=2&rawInputLstJSON=%5B%5D&curInstr=0


Good luck!


More information about the Tutor mailing list