What do you understand by true copy of a list? How is it different from shallow copy?


Answer :-

Shallow copy :-

A shallow copy is shallow because it only copies the object but not its child objects. Instead, the child objects refer to the original object’s child objects.


For example:-

import copy

# nested list (Lists inside a list )
First_List = [[99, 98, 97], [96, 95, 94], [93, 92, 91]]

# Making shallow copy of the First_List
Second_List = copy.copy(First_List)

print(id(First_List), id(Second_List))

Output :-

2055076765824
2055076766336


• The ID of First_List  is not the same as the ID of Second_List, Which is reasonable, Second_List  is a copy of the First_List.


Taking another example :-

• Here is where the shallowness becomes apparent. The IDs of the lists in the Second_List are equal to the IDs of the lists of the original First_List :


print(id(First_List[0]), id(Second_List[0]))

Output :-

2055108075008
2055108075008


• The shallowness means only the “outer” list gets copied. But the inner lists still refer to the lists of the original list. Because of this, changing a number in the copied list affects the original list.


Second_List[0][0] = 108
print(Second_List[0])
print(First_List[0])

Output :-

[108, 98, 97]
[108, 98, 97]


• The "external" list of Second_List  is the "real" copy of the original First_List. This way you can add new elements to it or even replace existing elements. These changes will not affect the original First_List list.


For example, let’s replace the first element which is a list in Second_List  with a string. This should not affect First_List.

Second_List[0] = "String"
print(Second_List)
print(First_List)

Output :-

String
[108, 98, 97]


Deep copy (True Copy)

import copy
# Lists inside a list
First_List = [[99, 98, 97], [96, 95, 94], [93, 92, 91]]
# Making deep copy of the First_List
Second_List = copy.deepcopy(First_List)

• A deep copy creates a completely independent copy of the original object.

• The IDs of First_List and Second_List do not match.

• The IDs of the lists in Second_List are not equal to the IDs of the lists in First_List.

• Changing a number in Second_List doesn’t change that value in the original First_List.

• The Second_List is an independent copy of First_List. Thus, there is no way changes made in Second_List would be visible in the original First_List.

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post