Shallow and Deep Copy in Python

Shallow and Deep Copy in Python

Shallow Copy

Shallow copy in Python allows to create a copy of objects. With shallow copy, the object references to the same memory and shares the value across the objects.

See the example below for different ways to shallow copy objects.

Assign objects to other objects with the "=" operator.

Performance: this approach is fastest as compared to [:] and deep copy

lista = [1,2, "thirdvalue", "fourthvalue"]

listb= lista

listb[0] = 3

print("Shallow copy - ")
print("Lista - ", lista)
print("Listb - ", listb)

Output-

Shallow copy - 
Lista -  [3, 2, 'thirdvalue', 'fourthvalue']
Listb -  [3, 2, 'thirdvalue', 'fourthvalue']

Assign the object to another object with [:]. This creates a new reference to the memory allocated for the list.

Performance: this approach is slower than the "=" operator as it creates a new reference.

lista = [1,2, "thirdvalue", "fourthvalue"]

listb= lista[:]

listb[0] = 3

print("Shallow copy - ")
print("Lista - ", lista)
print("Listb - ", listb)

Output-

Shallow copy - 
Lista -  [1, 2, 'thirdvalue', 'fourthvalue']
Listb -  [3, 2, 'thirdvalue', 'fourthvalue']

Deep Copy

Deep copy creates a new instance of the object and allocates different memory locations and the values associated are different from the copied/source object.

Below example uses deepcopy() method from the copy package.

Performance: This approach has a comprehensive operation and is slower than the above 2 approaches.

The deep copy won't call the constructor and copies the data with the new memory chunk.

import copy

lista = [1,2, "thirdvalue", "fourthvalue"]

listb= copy.deepcopy(lista)

listb[0] = 3

print("Shallow copy - ")
print("Lista - ", lista)
print("Listb - ", listb)
Shallow copy - 
Lista -  [1, 2, 'thirdvalue', 'fourthvalue']
Listb -  [3, 2, 'thirdvalue', 'fourthvalue']