Understanding Shallow and Deep Copies in Python


When working with complex data structures in Python, understanding the difference between shallow and deep copies is crucial. This knowledge helps prevent unexpected behavior in your code, especially when dealing with mutable objects like lists, dictionaries, and sets. In this blog, we’ll explore the concepts of shallow and deep copies, providing examples and use cases to help solidify your understanding.

Understanding Shallow Copy:

A shallow copy creates a new object, but instead of copying the nested objects, it copies references to them. As a result, changes made to mutable objects within the copied object will be reflected in the original object, and vice versa.

Creating Shallow Copies with the copy Module:

Python’s copy module provides a copy() function to create shallow copies of objects.

import copy

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

shallow_copied_list[1][0] = 99
print(original_list) # Output: [1, [99, 3], [4, 5]]

In this example, shallow_copied_list is a shallow copy of original_list. When we modify a nested list within shallow_copied_list, the change is reflected in original_list, showcasing the characteristic behavior of shallow copies.

Using Built-in Types’ copy Methods:

Several built-in types in Python provide a .copy() method for creating shallow copies.

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

original_dict = {'a': 1, 'b': 2}
copied_dict = original_dict.copy()

Understanding Deep Copy:

In contrast to shallow copies, a deep copy creates a new object along with recursive copies of nested objects. Changes to nested objects in the deep copy do not affect the original object, and vice versa.

Creating Deep Copies with the copy Module:

The copy module also provides a deepcopy() function for creating deep copies.

import copy

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

deep_copied_list[1][0] = 99
print(original_list) # Output: [1, [2, 3], [4, 5]]

In this example, deep_copied_list is a deep copy of original_list. Changes made to a nested list within deep_copied_list do not affect original_list.

Use Cases and Considerations:

Use shallow copies when you want to create a new object but maintain references to the original nested objects.
Use deep copies when you need a completely independent copy of an object and all its nested objects.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC