[Tutor] Re: Re: copies deep and shallow

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Feb 18 14:16:09 EST 2004



On Tue, 17 Feb 2004, Andrei wrote:

> Marilyn Davis wrote on Mon, 16 Feb 2004 11:07:33 -0800 (PST):
>
> >> Why would you use a (very slow) deepcopy when it doesn't offer any
> >> extra functionality? I can't modify integers/strings/tuples in-place,
> >> so I can't
> >
> > I see.  So deepcopy is slow, even for shallow objects?
>
> Well, if you try deepcopying that list of integers as I wrote in one of
> the earlier messages, you'll notice it's very slow compared to a shallow
> copy. And things don't get much shallower than integers :).


Hi Marilyn,


I think it might be more useful to concentrate on the effect of copy vs
deepcopy, rather than on its performance.  If copy.deepcopy() is slower,
that's only because it's doing something subtly different than
copy.copy().


We can see the difference with a matrix of numbers:

###
>>> matrix = [
... [0, 1, 0],
... [1, 0, 1],
... [1, 1, 1]]
>>> import copy
>>> m1 = copy.copy(matrix)
>>> m2 = copy.deepcopy(matrix)
###


We now have two "copies" of a matrix of numbers.  Let's make a change to
one of the elements:

###
>>> m1[0][0] = 42
>>> m1
[[42, 1, 0], [1, 0, 1], [1, 1, 1]]
###


Looks ok so far.  What happens to the others?

###
>>> m2
[[0, 1, 0], [1, 0, 1], [1, 1, 1]]
>>> matrix
[[42, 1, 0], [1, 0, 1], [1, 1, 1]]
###


Does this result surprise you?



Hope this helps!




More information about the Tutor mailing list