What is the difference between a deep copy and a shallow copy in Python?

Long Answer
Views 163

Answer:

In Python, a deep copy and a shallow copy are two different ways of copying an object.

A shallow copy is a copy of an object that references the same objects in memory as the original object. In other words, if the original object contains any references to other objects, the shallow copy will contain references to the same objects as the original.

For example:


original_list = [[1, 2], [3, 4]]
shallow_copy = original_list.copy()

print(original_list)  # [[1, 2], [3, 4]]
print(shallow_copy)   # [[1, 2], [3, 4]]

original_list[0][0] = 10

print(original_list)  # [[10, 2], [3, 4]]
print(shallow_copy)   # [[10, 2], [3, 4]]

A deep copy, on the other hand, is a complete copy of an object and all the objects it references. The deep copy has no references to the original object or any of its referenced objects.

For example:


import copy

original_list = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(original_list)

print(original_list)  # [[1, 2], [3, 4]]
print(deep_copy)      # [[1, 2], [3, 4]]

original_list[0][0] = 10

print(original_list)  # [[10, 2], [3, 4]]
print(deep_copy)      # [[1, 2], [3, 4]]

In general, you should use a shallow copy if you want to make a copy of an object that shares references to other objects, and a deep copy if you want to make a completely independent copy of an object and all the objects it references.

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Python, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.