0

I am trying to understand what happens when I assign a list (list1) into another variable (list2) and concatenate a third list with (list3).

list1 = [3,4]
list2=list1 # shallow copy/hard copy
list1 = list1 + [10,11]
print(list1)
print(list2)

If I apply the Shallow copy or Hard copy concept it should print 
[3, 4, 10,10]
[3, 4, 10,11]

But in practice I get 
[3, 4]
[3, 4, 10, 11]
Can anyone please explain what is happening in this code snippet? I use   Python 3.6 

2 Answers2

0

Even though list1 and list2 are two names for the same object (confirm with list1 is list2), you actually create a new object when you add another list with list1 = list1 + [10, 11]. If you want to modify list1 in-place, use list1 += [10, 11]. Then you will get what you expected.

cbrnr
  • 1,564
  • 1
  • 14
  • 28
-1

As far as i know In case of shallow copy, a reference of object is copied in other object. It means that any changes made to a copy of object do reflect in the original object, and while in a hard copy the change is not reflected back to the original object, so it depends on what type of copy you used.