Python Shallow copy vs Deep Copy

This article explains about shallow copy and deep copy in python

Hello all. Today we will see shallow copy vs deep copy in Python.

Shallow Copy:

import copy

# Let a be list with some values
a = [1,2,3,4,5]

# shallow copy a into b
b = copy.copy(a)

# append 10 into b
print(a)
print(b)
# output
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

# So far good , Let's have some complex values and try

a = [1,2,3,4, [1,2]]

b = copy.copy(a)

# change value of index 4 inside b
b[4][0] = 10

print(a)
print(b)

# output
[1, 2, 3, 4, [10, 2]]
[1, 2, 3, 4, [10, 2]]

As you see it got changed in a list also which we don't want to happen. Clearly we need something to copy entire list and change the copy alone not original one.

Deep Copy:

   Deep copy solves the problem we faced above in shallow copy. It copies entire list into new list and changes to any level in copied list doesn't affect the original one


import copy


a = [1,2,3,4, [1,2]]

b = copy.deepcopy(a)


# change value of index 4 inside b
b[4][0] = 10

print(a)
print(b)

# output
[1, 2, 3, 4, [1, 2]]
[1, 2, 3, 4, [10, 2]]
As you see deep copy , copies entire level . Thanks for reading . Happy coding.

Leave a comment

(Note: Comments are moderated)