The shallow copy created by copy() is a new container populated with references to the contents of the original object. When making a shallow copy of a list object, a new list is constructed and the elements of the original object are appended to it.
In [7]:
import copy
class MyTry:
def __init__(self):
self.lst = [1,2,3,4,5]
a = MyTry()
dup = copy.copy(a)
a.lst.append(6)
print(a.lst, dup.lst)
print(id(a), id(dup))
In [8]:
import copy
class MyTry:
def __init__(self):
self.lst = [1,2,3,4,5]
a = MyTry()
dup = copy.copy(a)
a.lst.append(6)
print(a.lst, dup.lst)
print(id(a), id(dup))
print(id(a.lst), id(dup.lst))
The deep copy created by deepcopy() is a new container populated with copies of the contents of the original object. To make a deep copy of a list, a new list is constructed, the elements of the original list are copied, and then those copies are appended to the new list.
Replacing the call to copy() with deepcopy() makes the difference in the output apparent.
In [1]:
import copy
class MyTry:
def __init__(self):
self.lst = [1,2,3,4,5]
a = MyTry()
dup = copy.deepcopy(a)
a.lst.append(6)
print(a.lst, dup.lst)
print(id(a), id(dup))
print(id(a.lst), id(dup.lst))
In [2]:
lst = [1,2,3,4,5]
dup_lst = copy.deepcopy(lst)
print(id(lst), id(dup_lst))
In [3]:
import copy
class MyTry:
def __init__(self):
self.lst = [1,2,3,4,[5]]
a = MyTry()
dup = copy.deepcopy(a)
a.lst.append(6)
print(a.lst, dup.lst)
print(id(a), id(dup))
print(id(a.lst), id(dup.lst))
It is possible to control how copies are made using the copy() and deepcopy() special methods.