[Tutor] copies deep and shallow
Marilyn Davis
marilyn at deliberate.com
Fri Feb 13 02:03:40 EST 2004
Hello Pythoners,
OK. I'm stumped again.
>>> print dict.copy.__doc__
D.copy() -> a shallow copy of D
And from the copy module:
>>> print copy.__doc__
- A shallow copy constructs a new compound object and then (to the
extent possible) inserts *the same objects* into in that the
original contains.
- A deep copy constructs a new compound object and then, recursively,
inserts *copies* into it of the objects found in the original.
So, here's my code:
#!/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'
print 'Original combos:', combos
print ' combos2:', combos2
no_liver = copy.deepcopy(combos)
del no_liver['liver']
print 'Original combos:', combos
print ' no_liver:', no_liver
##### end of code
And the output:
bash-2.05a$ ./copies.py
Original combos: {'steak': 'lobster', 'liver': 'onions'}
combos2: {'steak': 'eggs', 'liver': 'onions'}
Original combos: {'steak': 'lobster', 'liver': 'onions'}
no_liver: {'steak': 'lobster'}
bash-2.05a$
---
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.
So I'm out to lunch some how.
Can anyone help?
Marilyn
--
More information about the Tutor
mailing list