Shallow vs Deep copies [was Re: python assignment]

Erik Max Francis max at alcyone.com
Wed Jul 23 21:18:56 CEST 2003


Jim Richardson wrote:

> A shallow copy of an object, returns an object that contains
> references
> to objects within the copied object, yes?
> 
> so a list consisting of [1,2,a,"a"] when copied shallowly, will return
> exactly that, but when copied deeply, will reture [1,2,"whatever a
> points to","a"] yes?

No, that's what the first list already consists of:

>>> a = "whatever a points to"
>>> l1 = [1, 2, a, "a"]
>>> l1
[1, 2, 'whatever a points to', 'a']

A shallow copy makes a new object of the object passed in, and maintains
the same reference.  A deep copy makes a new object, _and_ a new object
of all references it contains, and on down the line.

The difference between shallow and deep copying is not apparent when
you're talking about immutable objects, since immutable objects need not
ever be literally copied.  Consider a simpler case of a list containing
a single element, which is an instance of a custom class:

>>> class C: pass
... 
>>> c = C()
>>> x = [c]
>>> y = copy.copy(x)
>>> x is y
0
>>> x[0] is y[0]
1
>>> z = copy.deepcopy(x)
>>> x is z
0
>>> x[0] is z[0]
0
>>> x[0]
<__main__.C instance at 0x810ba8c>
>>> z[0]
<__main__.C instance at 0x814c9fc>

Shallow copying makes a duplicate of the parent object.  Deep copying
makes a duplicate of everything.

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ Of war men ask the outcome, not the cause.
\__/  Seneca




More information about the Python-list mailing list