Reputation: 1201
I am trying to understand behind the code operation in shallow copy in python
created an object
o = [1,12,32,423,42,3,23,[1,2,3,4]]
created a shallow copy and assigned to a variable
r = copy.copy(o)
print(r)
[1, 12, 32, 423, 42, 3, 23, [1, 2, 3, 4]]
Then tried to assigning new value in two different indexes
o[1]="ff"
o[7][1]="kk"
print(r)
[1, 12, 32, 423, 42, 3, 23, [1, 'kk', 3, 4]]
So as per shallow copy it creates reference of parent in child variable so when we change parent, it reflects in child, but here reference changed only in sublist only. Why so?
Upvotes: 0
Views: 58
Reputation: 4630
Try to observe what is happening by running the below code (after the modifications):
print(id(r[1]))
print(id(o[1])) # different
print(id(r[7]))
print(id(o[7])) # same
print(id(r[7][1]))
print(id(o[7][1])) # same
Also, read the links that others have posted.
Upvotes: 1