[Tutor] Re: copies deep and shallow

Marilyn Davis marilyn at deliberate.com
Sun Feb 15 02:25:40 EST 2004

On Fri, 13 Feb 2004, Andrei wrote:

> Marilyn Davis wrote on Fri, 13 Feb 2004 09:21:31 -0800 (PST):
> <snip>
> > So shallow copies are independent at the first level but dependent at
> > deeper levels.
> I'm not sure what you mean by "deeper levels". If your whatever you copy
> only contains immutable components (string, numbers, tuples), there isn't
> really any danger in this because you can't change them in-place anyway
> (ragardless of how many levels deep the tuple is for example).
> > Why would someone want a shallow copy?  It seems like trouble lurking.
> Try this in the interactive interpreter: 
> a = range(2000000) # make that 4mln if you have 512 MB or 1mln for 128MB
> b = copy.deepcopy(a)
> c = copy.copy(a)
> Noticed any difference? Also it's not dangerous if you're using immutable
> items.

Thank you.

But how is c = copy.copy(a) better than c = a in this example?

Is it true that a = b.copy() does the same thing as a = copy.copy(b) for

And is it true that for lists, a = b[:] does the same thing as a =

> > I would think you'd either want a completely deep copy, or a reference to
> > the same everything.
> Generally I use deepcopy just to be on the safe side, but that's not such a
> big problem since I don't tend to use very large amounts of data when
> copying.

I would think it would be unusual to make a copy of dictionary, deep
or shallow.  I would think that you usually need a reference because
you keep data in dictionaries and you don't want a branch in your data
-- unless you do want a branch in your data.

Or maybe you want a deep copy when you pass your dictionary to an
unknown function and you want to be sure it doesn't mess with your

When would you prefer a shallow copy of a dictionary over a reference
to a dictionary?  I can't think of an example of that.

I can't get beyond thinking that you either want a deep copy or a
reference.  I must be missing something because there appears to be
two ways to make shallow copies for dictionaries and for lists.  There
must be a good reason.

Any insights would be appreciated.

Thank you again.




More information about the Tutor mailing list