0

Shallow Copy VS. Deep Copy in Python

On a website this statement is mentioned: "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." But with my example this doesn't work old_list = [1,3,5] new_list = old_list.copy() new_list.append(8) print(old_list) print(new_list) OUTPUT: [1, 3, 5] [1, 3, 5, 8]

1st Jun 2019, 11:48 PM
harshit
harshit - avatar
3 Respostas
+ 1
~ swim ~ That seems to work but if I change the whole inner list then this doesn't work. old_list = [1,3,[5,6]] new_list = old_list.copy() new_list[2]= [2,0] print(old_list) print(new_list) OUTPUT: [1, 3, [5, 6]] [1, 3, [2, 0]] Why?
2nd Jun 2019, 3:08 PM
harshit
harshit - avatar
+ 1
I agree with what ~ swim ~ said. In your second example, the object at index 2 in new_list is being replaced. The object itself is not modified, only the reference is lost. So new_list[2] no longer points to the same object. The address also changes, as can be checked using id(). old_list = [1,3,[5,6]] new_list = old_list.copy() new_list[2].append(7) print(id(old_list[2]), id(new_list[2])) new_list[2]= [2,0] print(id(old_list[2]), id(new_list[2]))
3rd Jun 2019, 11:06 AM
Kishalaya Saha
Kishalaya Saha - avatar
0
Kishalaya Saha please see this.
3rd Jun 2019, 9:02 AM
harshit
harshit - avatar