Reputation: 24500
When using copy() it creates a totally new data, the change to kvps does not affect theCopy var?
aList = [1,2]
bList = [3,4]
kvps = { '1' : aList, '2' : bList }
theCopy = kvps.copy() # this creates totally new copy, not a reference?
kvps['1'][0] = 5 #this var kvps becomes { '1' : [5,2], '2' : [3,4] }?
sum = kvps['1'][0] + theCopy['1'][0] #must be 5+1 = 6
print(sum)
But the correct answer is 10? Why?
After kvps.copy() - does it mean that theCopy 'follows' whatever changes are done to kvps? But this is called reference? I m confused about the terms copy() and reference..
Upvotes: 0
Views: 246
Reputation: 78700
You are creating a shallow copy of your dict, which in practice means that you can (re)assign keys in both dicts idependently as the original dict and the copy don't refer to the same object in memory. The values however are not copied.
>>> kvps
>>> {'1': [1, 2], '2': [3, 4]}
>>> copy = kvps.copy()
>>> copy['5'] = [5, 6]
>>> kvps
>>> {'1': [1, 2], '2': [3, 4]}
>>> copy
>>> {'1': [1, 2], '2': [3, 4], '5': [5, 6]}
If you want to make a deep copy of the values, use copy.deepcopy
.
>>> from copy import deepcopy
>>> the_deepcopy = deepcopy(kvps)
>>> kvps['1'][0] = 5
>>> kvps['1'][0]
>>> 5
>>> copy['1'][0]
>>> 5
>>> the_deepcopy['1'][0]
>>> 1
Upvotes: 1
Reputation: 108
copy is a shallow copy, it still holds a reference to its original source. If you want The copy to be a different object all together, then you need to import the copy module and use the deepcopy method
import copy
aList = [1,2]
bList = [3,4]
kvps = { '1' : aList, '2' : bList }
theCopy = copy.deepcopy(kvps) # this creates totally new copy, not a reference? yes
kvps['1'][0] = 5 #this var kvps becomes { '1' : [5,2], '2' : [3,4] }? yes
sum = kvps['1'][0] + theCopy['1'][0] #must be 5+1 = 6
print(sum)
Upvotes: 1