A question about python deepcopy and shallow copy.
the post at What is the difference between a deep copy and a shallow copy?
cannot help me.
why e.g. 1 's sum is 6 not 10 ?
e.g.1 :
kvps = { '1' : 1, '2' : 2 }
theCopy = kvps.copy() # both point to the same mem location ?
kvps['1'] = 5
sum = kvps['1'] + theCopy['1']
print sum
output sum is 6
e.g.2 :
aList = [1,2]
bList = [3,4]
kvps = { '1' : aList, '2' : bList }
theCopy = kvps.copy() # both point to the same mem location ?
kvps['1'][0] = 5
sum = kvps['1'][0] + theCopy['1'][0]
print sum
output sum is 10
e.g.3 :
import copy
aList = [1,2]
bList = [3,4]
kvps = { '1' : aList, '2' : bList }
theCopy = copy.deepcopy(kvps)
kvps['1'][0] = 5
sum = kvps['1'][0] + theCopy['1'][0]
print sum
output sum is 6.
Also , e.g. 4
kvps = { '1' : 1, '2' : 2 }
theCopy = dict(kvps) # theCopy hold a reference to kvps ?
kvps['1'] = 5 # should also change theCopy , right ?
sum = kvps['1'] + theCopy['1']
print kvps
print theCopy
print sum
its sum is 6 , if theCopy is a reference to kvps , it should be 10.
Shallow copy makes a copy of mutable objects in the top-level container. A deep copy makes a new instance of all mutable containers in the data structure.
"e.g. 2" results in 10 because you copy the dict on the outside, but the two lists inside are still the old lists, and lists can be changed in-place (they're mutable).
Deep copy makes runs aList.copy(), bList.copy() and replaces the values in your dict with their copies.
e.g. 1 explained:
When you apply this to e.g. 2:
The list objects in both dicts are the same objects, so modifying one of the lists will be reflected in both dicts.
Doing a deep copy (e.g. 3) results in this:
This means both dicts have entirely different contents, and modifying one won't modify the other.
e.g. 4 via
dict()
is equivalent to a shallow copy.e.g.1
In this example you make copies of the keys but not the objects they point to. Changing what one key points to does not change the copy of that key. This is because the copy of the key exists in a different place in memory and will only point to the same object until it is reassigned. The reassignment of one of the copies does not change the other which is why you get 6.
e.g.2
The keys are copied. Both keys point to the same objects. The assignment the modifies the object that both keys point to (although both keys are in different places in memory) which is why the change is seen in both in the sum.
e.g.3
Everything is copied. Each key points to its own copy of the objects. There are now two "aList"s in memory. The aList pointed to by KVPS is changed while the "aList" pointed to by COPY is not.
http://docs.python.org/library/copy.html