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)


#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]]

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 :



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


A Senior Software Developer/Body builder . to help others enjoy coding and stay healthy