[Tutor] Re: Re: copies deep and shallow
Marilyn Davis
marilyn at deliberate.com
Wed Feb 18 15:22:27 EST 2004
On Wed, 18 Feb 2004, Danny Yoo wrote:
>
>
> 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?
No. I'm getting it.
The nested list, since it's mutable, is a reference in the copy() but a
new object in the deepcopy.
>
>
>
> Hope this helps!
>
>
Thank you. It does. I'm getting more confident.
You folks are great!
Marilyn
--
More information about the Tutor
mailing list