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

Max Erickson maxerickson at gmail.com
Sun Sep 4 17:41:41 EDT 2005


"Alex" <lidenalex at yahoo.se> wrote in
news:1125863497.723200.178620 at z14g2000cwz.googlegroups.com: 
>>>> D={'Python': 'good', 'Basic': 'simple'}
>>>> E=D.copy()
>>>> E
> {'Python': 'good', 'Basic': 'simple'}
>>>> D['Basic']='oh my'
>>>> D
> {'Python': 'good', 'Basic': 'oh my'}
>>>> E
> {'Python': 'good', 'Basic': 'simple'}
>>>>
> 
> Hmm, this looks like a deep copy to me?? I also tried
> 

It is shallow, but strings are immutable so the difference is fairly 
moot.

>>>> D={'Python': 'good', 'Basic': 'simple'}
>>>> E=D
>>>> E
> {'Python': 'good', 'Basic': 'simple'}
>>>> E['Basic']='oh my'
>>>> E
> {'Python': 'good', 'Basic': 'oh my'}
>>>> D
> {'Python': 'good', 'Basic': 'oh my'}
>>>>
> 

Here, E and D are different names for the same object. There is no 
copy.

> which looks like a shallow copy to me?? So my hypothesis is that
> E=D is a shallow copy while E=D.copy() is a deep copy.
> 

> So is the documentation wrong when they claim that D.copy()
> returns a shallow copy of D, or did I misunderstand the
> difference between a deep and shallow copy?

Sort of, some examples:

Here d1 and d2 are copies. They can be independently changed to 
refer to different objects:

>>> d1={'a':1,'b':2}
>>> d2=d1.copy()
>>> d1['a']=3
>>> d2['b']=4
>>> d1
{'a': 3, 'b': 2}
>>> d2
{'a': 1, 'b': 4}

Again, d3 and d4 are copies, but instead of changing the objects 
they refer to, we change the contents of the objects they refer to:

>>> d3={'c':[3],'d':[4]}
>>> d4=d3.copy()
>>> d3['c'][0]=5
>>> d4['d'][0]=6
>>> d3
{'c': [5], 'd': [6]}
>>> d4
{'c': [5], 'd': [6]}

Both cases are shallow copies. In a deep copy, altering the contents 
of d3['c'] would have no impact on the contents of d4['c'].

max



More information about the Python-list mailing list