[Tutor] copies deep and shallow

Michael Janssen Janssen at rz.uni-frankfurt.de
Fri Feb 13 04:15:35 EST 2004


On Thu, 12 Feb 2004, Marilyn Davis wrote:

> #!/usr/bin/env python2.2
> '''Trying to demonstrate deep/shallow copies of dictionaries'''
>
> import copy
> combos = {'steak':'lobster', 'liver':'onions'}
> combos2 = combos.copy()
> combos2['steak'] = 'eggs'

value 'lobster' might have been the same internal object as in
combos['steak']. But here 'steak' gets reassigned. You could try to
*change* the string in place, but you will fail, because you can't
change strings in place:

>>> import copy
>>> immutable = {"aString": "here"}
>>> immutable2 = copy.copy(immutable)
>>> immutable["aString"] += " and there"
>>> immutable
{'aString': 'here and there'}
>>> immutable2
{'aString': 'here'}



> I thought that when I changed combos2's 'lobster' to 'eggs', that the
> original combos would be affected.  I thought that that is what a
> shallow copy meant.

You actually need a nested data structur to show the effects of
non-recursive copy ;-) Put another (mutable) container type within your
dict and then change the content of this object:

>>> lvl1 = {"lvl2": [1,2,3]}
>>> lvl1_copy = copy.copy(lvl1)
>>> lvl1["lvl2"][0] = 4 # reassigning within lvl2
>>> lvl1
{'lvl2': [4, 2, 3]}
>>> lvl1_copy
{'lvl2': [4, 2, 3]}

---> 'lvl2' list was 'shared' between the two copies of the dictionary.
With copy.deepcopy the 'lvl2' list would have been created as a copy too.

Michael



More information about the Tutor mailing list