0

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
Chidananda Nayak
  • 1,161
  • 1
  • 13
  • 45
  • 1
    Possible duplicate of [What exactly is the difference between shallow copy, deepcopy and normal assignment operation?](https://stackoverflow.com/questions/17246693/what-exactly-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignm) – Azat Ibrakov Sep 14 '19 at 06:25
  • Your example has covered [here](https://stackoverflow.com/a/50198542/8353711) – shaik moeed Sep 14 '19 at 06:40

1 Answers1

1

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.

Dipen Dadhaniya
  • 4,550
  • 2
  • 16
  • 24
  • i tried to print ids before assigning to their index o = [1,12,32,423,42,3,23,[1,2,3,4]] r = copy.copy(o) print(id(o[1]),id(r[1])) . O/P is 1774052288 1774052288 same – Chidananda Nayak Sep 14 '19 at 06:51
  • 1
    Also, print after the modifications. – Dipen Dadhaniya Sep 14 '19 at 06:52
  • okay so after modification ids are 69169280 1774052288, different... So, in list id changes of respective index but in sublist id remains same. But Why? – Chidananda Nayak Sep 14 '19 at 06:59
  • 1
    To understand that, try to run this code and observe: "import sys arr1 = [1, 2, 3] print(sys.getsizeof(arr1)) arr2 = [1, 2, ['a', 'b', 'c', 'd']] print(sys.getsizeof(arr1)) " – Dipen Dadhaniya Sep 14 '19 at 07:04