Skip to main content

8.16) Copying Mutable Objects


For mutable objects, you need to be specific when you want to make copies, since they could be modified without you noticing.

Remember, we’ve already seen how you can make copies of lists by slicing the whole range of values:

mylist=[1,2,3]
samelist=mylist  # this is just referencing the same list,
                 # i.e. any change to ‘mylist’ will also change ‘samelist’
listcopy=mylist[:] # this is a copy of mylist

For dictionaries, you can use the method copy():

mydict={'a':1,'b':2,'c':3}
samedict=mydict        # this is just referencing the same dictionary
dictcopy=mydict.copy() # this is a copy of mydict

The following PythonTutor code shows what happens when you reference and copy lists and dictionaries.

[advanced_iframe securitykey="cdcd195854f0661ec0561aa6e33a487eadfbcbcc" src="http://pythontutor.com/iframe-embed.html#code=%23+copying+lists%0Amylist%3D%5B1,2,3%5D%0Alistcopy%3Dmylist%5B%3A%5D+%0Aprint+listcopy%0A%0Amylist%5B1%5D%3D%22two%22%0Aprint+mylist%0Aprint+listcopy%0A%0A%0A%23+copying+dictionaries%0Amydict%3D%7B%22a%22%3A1,%22b%22%3A2,%22c%22%3A3%7D%0Adictcopy%3Dmydict.copy()%0Aprint+dictcopy%0Amydict%5B%22b%22%5D%3D%22two%22%0Aprint+mydict%0Aprint+dictcopy&cumulative=false&heapPrimitives=false&drawParentPointers=true&textReferences=false&showOnlyOutputs=false&py=2&curInstr=0"]