-1

I have two sets of code which demonstrate shallow copy but I am not able to explain why the code behaves differently.

The first set of code:

import copy
cv1 = [1,2,3]
cv2 = copy.copy(cv1)

print(cv1)
print(cv2)

cv2[0] = 0
cv1[1] = 1

print(cv1)
print(cv2)

The output :

[1, 2, 3]
[1, 2, 3]
[1, 1, 3]
[0, 2, 3] 

Second set of code:

import copy

a = [ [1, 2, 3], [4, 5, 6] ]
b = copy.copy(a)

print(a)
print(b)

a[1][2] = 25
b[0][0] = 98

print(a)
print(b)

The output :

[[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]
[[98, 2, 3], [4, 5, 25]]
[[98, 2, 3], [4, 5, 25]]

In my understanding, both codes should do the exact same thing. Why is that after the second set of print statements in each code snippet, the contents of cv1 and cv2 are different while a and b are the same.? Maybe it is a very basic error on my side, I am new to Python, but I can't seem to figure this out. Any help is appreciated.

pppery
  • 3,731
  • 22
  • 33
  • 46
  • because your 2nd exanple is a list holding _references_ to list. You copy the _reference_ - NOT the data behind it. – Patrick Artner Aug 01 '20 at 18:50
  • See answers on [list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent) that handle it to exhausting – Patrick Artner Aug 01 '20 at 18:51

1 Answers1

1

This has to do with the copy library you imported.

copy.copy(x)

Return a shallow copy of x.

A shallow copy constructs a new compound object and then (to the extent possible) inserts > references into it to the objects found in the original.

So in the first case the copy is creating a new list of int object while the second case it is creating a list of references object.

While in the second case the list a and b are different, they contain the same lists inside. Thats why changing one of those list inside will edit both lists.

For the two cases to be the same you need to use the copy.deepcopy function.

Carl Kristensen
  • 451
  • 3
  • 14