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

Alex lidenalex at yahoo.se
Sun Sep 4 15:51:37 EDT 2005


Entering the following in the Python shell yields

>>> help(dict.copy)
Help on method_descriptor:

copy(...)
    D.copy() -> a shallow copy of D

>>>

Ok, I thought a dictionary copy is a shallow copy. Not knowing exactly
what that meant I went to http://en.wikipedia.org/wiki/Deep_copy where
I could read

"...a deep copy is copy that contains the complete encapsulated data of
the original object, allowing it to be used independently of the
original object. In contrast, a shallow copy is a copy that may be
associated to data shared by the original and the copy"

Going back to Python shell I tested the following

>>> 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

>>> 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'}
>>>

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?

Thanks




More information about the Python-list mailing list