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

In Python, deep copy and shallow copy are two different methods of copying objects.

  1. Shallow Copy:

    A shallow copy creates a new object, but the elements within that object are references to the elements in the original object. This means that the elements in the new object and the original object point to the same memory address. When you modify an element in the new object, the corresponding element in the original object will also change accordingly. In Python, you can use the copy() method to perform a shallow copy.

import copy

a = [1, 2, [3, 4]]
b = copy.copy(a)

b[2][0] = 5
print(a)  # [1, 2, [5, 4]]
  1. Deep copy:
    Deep copy is creating a new object, while recursively copying the elements from the original object, so that the elements in the new object are completely independent of the elements in the original object. Modifying the elements in the new object will not affect the elements in the original object. In Python, you can use the deepcopy() method to perform a deep copy.
import copy

a = [1, 2, [3, 4]]
b = copy.deepcopy(a)

b[2][0] = 5
print(a)  # [1, 2, [3, 4]]

In general, shallow copying only copies one layer of reference relationships of an object, while deep copying recursively copies all reference relationships of an object, creating a completely new object. Deep copying consumes more time and memory resources than shallow copying, but ensures complete independence between objects.

Leave a Reply 0

Your email address will not be published. Required fields are marked *