Python shallow copy and deep copy
shallow copy
a1 = [[1,2],[3,4]]
a2_1 = a1[:]
a2_2 = list(a1)
a2_3 = copy.copy(a1)
deep copy
>>> import copy
>>> a3 = copy.deepcopy(a1)
test
#now change original array value
>>> a1[0][0] = 0
>>> a2_1
[[0, 2], [3, 4]]
>>> a2_2
[[0, 2], [3, 4]]
>>> a2_3
[[0, 2], [3, 4]]# >>> a3
# [[1, 2], [3, 4]]
Conclusion
shallow copy copied the reference of top level objects so nested object value still follows original element.
deep copy copied all levels of objects values and create new reference .so nested level object value is fully independent from original element value .but of course deep copy slower (depends on nested level and number of objects on each level).
The the same applied to class
class P:
def __init__(self , x, y):
self.x = x
self.y = y
def __repr__(self):
return f'({self.x},{self.y})'
def __str__(self):
return f'({self.x},{self.y})'
class L:
def __init__(self, points):
self.points = points
def __repr__(self):
return ','.join([str(p) for p in self.points])l1 = L([P(i,i+1) for i in range(0, 10)])
#shallow copy
l2_1 = copy.copy(l1)
l2_2 = L(l1.points[:])#deep copy
l3 = copy.deepcopy(l1)#change original object property
l1.points[0].x= 100
print (l2_1)
print (l2_2)
print (l3)
Output :
(100,1),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9),(9,10)
(100,1),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9),(9,10)
(0,1),(1,2),(2,3),(3,4),(4,5),(5,6),(6,7),(7,8),(8,9),(9,10)