pythonlistshallow-copy

Shouldn't shallow copy create an object with different id in python?


list1 = [1,2,3]
list2 =list1
id(list1[0]) == id(list2[0])  #True
id(list1) == id(list2)        #True

I am trying to learn the concept of deep copy and shallow copy. I understand that list1 and list2 would be references to the same memory, therefore id(list1[0]) will be equal to id(list2[0]). But shouldn't id(list1) be different from id(list2) as both are different objects of class list.


Solution

  • In python, assignment never copies data. You just get a new name that references the same value.

    There are basically three cases:

    Assignment: just a new name that points to the same object.

    copy.copy the object itself is copied, but members of the object are not. So a shallow copy of a list will be a new list, have a new ID but will point to the same objects in memory for its elements as the original list.

    copy.deepcopy recursively copies everything.

    Good resources: http://www.pythontutor.com/visualize.html#mode=edit

    Ned Batchelder, Facts and myths about python names and values https://youtu.be/_AEJHKGk9ns