is dict.copy() a deep copy or a shallow copy

Alex lidenalex at yahoo.se
Mon Sep 5 03:01:22 EDT 2005


Thanks max,
Now it's much clearer. I made the following experiment
>>>#1
>>> D={'a':1, 'b':2}
>>> D
{'a': 1, 'b': 2}
>>> E=D.copy()
>>> E
{'a': 1, 'b': 2}
>>> D['a']=3
>>> D
{'a': 3, 'b': 2}
>>> E
{'a': 1, 'b': 2}
>>>#2
>>> D={'a':[1,3], 'b':[2,4]}
>>> D
{'a': [1, 3], 'b': [2, 4]}
>>> E=D.copy()
>>> E
{'a': [1, 3], 'b': [2, 4]}
>>> D['a'][0]=9
>>> D
{'a': [9, 3], 'b': [2, 4]}
>>> E
{'a': [9, 3], 'b': [2, 4]}
>>>#3
>>> import copy
>>> F=copy.deepcopy(D)
>>> D
{'a': [9, 3], 'b': [2, 4]}
>>> F
{'a': [9, 3], 'b': [2, 4]}
>>> D['a'][0]=7
>>> D
{'a': [7, 3], 'b': [2, 4]}
>>> F
{'a': [9, 3], 'b': [2, 4]}
>>>

A shallow copy of an object is a copy of the first-level data members
and if one of the members is a pointer, then only the pointer value is
copied, not the structure pointed to by the pointer. The original
object and its shallow copy share the memory space occupied by these
structures.
A deep copy of an object is a copy of everything (including the
structures pointe to by the pointers). The original object and its deep
copy do not share any memory space.

In #1 no pointers are involved so changing a value affects only D but
not E.

In #2 D['a'] and E['a'] are pointers that both point to the same memory
space. Changing that memory space doesn't change the pointers
themsleves.

In #3 a deepcopy makes sure that a copy is made not just of the
pointers but also of the things pointed to.

So the lesson to be learned is that if you make a copy of a dictionary
whose values are pointers to other structures then a deepcopy prevents
a coupling between a the original and the copy. 

Alex




More information about the Python-list mailing list