[Tutor] copies deep and shallow

Marilyn Davis marilyn at deliberate.com
Fri Feb 13 12:21:31 EST 2004


On Fri, 13 Feb 2004, Michael Janssen wrote:

> On Thu, 12 Feb 2004, Marilyn Davis wrote:
> 
> > #!/usr/bin/env python2.2
> > '''Trying to demonstrate deep/shallow copies of dictionaries'''
> >
> > import copy
> > combos = {'steak':'lobster', 'liver':'onions'}
> > combos2 = combos.copy()
> > combos2['steak'] = 'eggs'
> 
> value 'lobster' might have been the same internal object as in
> combos['steak']. But here 'steak' gets reassigned. You could try to
> *change* the string in place, but you will fail, because you can't
> change strings in place:
> 
> >>> import copy
> >>> immutable = {"aString": "here"}
> >>> immutable2 = copy.copy(immutable)
> >>> immutable["aString"] += " and there"
> >>> immutable
> {'aString': 'here and there'}
> >>> immutable2
> {'aString': 'here'}

Thank you.  I think I see.

So shallow copies are independent at the first level but dependent at
deeper levels.

Why would someone want a shallow copy?  It seems like trouble lurking.

I would think you'd either want a completely deep copy, or a reference to
the same everything.

I must still be missing something.

Marilyn
> 
> 
> > I thought that when I changed combos2's 'lobster' to 'eggs', that the
> > original combos would be affected.  I thought that that is what a
> > shallow copy meant.
> 
> You actually need a nested data structur to show the effects of
> non-recursive copy ;-) Put another (mutable) container type within your
> dict and then change the content of this object:
> 
> >>> lvl1 = {"lvl2": [1,2,3]}
> >>> lvl1_copy = copy.copy(lvl1)
> >>> lvl1["lvl2"][0] = 4 # reassigning within lvl2
> >>> lvl1
> {'lvl2': [4, 2, 3]}
> >>> lvl1_copy
> {'lvl2': [4, 2, 3]}
> 
> ---> 'lvl2' list was 'shared' between the two copies of the dictionary.
> With copy.deepcopy the 'lvl2' list would have been created as a copy too.
> 
> Michael
> 

-- 




More information about the Tutor mailing list