What is the difference between a shallow copy and a deep copy in Python?
In Python, the terms “shallow copy” and “deep copy” refer to two different ways of copying data structures, such as lists or dictionaries. The main difference between them lies in how they handle nested objects or compound objects (objects containing other objects).
Shallow copy
A shallow copy creates a new object, but does not create copies of the nested objects within the original object. Instead, it copies only the references to the nested objects. As a result, any changes made to the nested objects in the copied structure will also be reflected in the original structure, and vice versa.
You can create a shallow copy of a list or dictionary using the copy
method of the copy
module, or by using slicing (for lists) or the .copy()
method (for dictionaries).
import copy
original_list = [1, [2, 3], 4]
shallow_copied_list = copy.copy(original_list)
Deep copy
A deep copy creates a new object and recursively copies all the nested objects within the original object. This means that the new object and its nested objects are completely independent of the original object and its nested objects. Changes made to the nested objects in the copied structure will not affect the original structure, and vice versa.
You can create a deep copy of a list or dictionary using the deepcopy
method of the copy
module.
import copy
original_list = [1, [2, 3], 4]
deep_copied_list = copy.deepcopy(original_list)
To summarize, a shallow copy creates a new object with references to the original nested objects, while a deep copy creates a new object with copies of all the nested objects, making them independent of the original object.