I'm having trouble understanding the difference between a deep copy and a shallow copy. Working on an assignment and when a method returns an instance variable, we're meant to return a copy of it to prevent aliasing, but this concept wasn't really reviewed in class and the professors are honestly unhelpful, so I'm utterly lost.
1 Answers
who explains better than python itself :
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
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.
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
Two problems often exist with deep copy operations that don’t exist with shallow copy operations:
Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.
Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.
The deepcopy() function avoids these problems by:
keeping a memo dictionary of objects already copied during the current copying pass; and
letting user-defined classes override the copying operation or the set of components copied.
Source : Python
Simple explanation is deep copies will change when the original variable changes because they use the same memory location, but shallow copies are like separate from the original variable.
myList = [1,2,3,4,5]
DeepList = myList # Deep Copy (uses the same memory location)
myList[0] = 5
print(DeepList) # [5, 2, 3, 4, 5]
anotherList = [1,2,3,4,5]
ShallowList = anotherList[:]
anotherList[0] = 5
print(anotherList) # [5, 2, 3, 4, 5]
print(ShallowList) # [1, 2, 3, 4, 5]
you can convert a list from Deep-Copy to Shallow-Copy using [:]
and for dicts you can use .copy()
example :
myList = [1,2,3,4,5]
myDict = {'firstname':'Abolfazl','lastname':'ghaemi'}
myShallowListCopy = myList[:]
myShallowDictCopy = myDict.copy()
Shallow Copies are much faster than deep copies

- 424
- 2
- 14