What you need to know about Shallow and Deep Copy in Python

Sometimes you'll want to copy an object completely, but other times you'll want to use it as a reference. At this time, you need Shallow and Deep Copy when programming in Python.

Sometimes you'll want to copy an object completely, but other times you'll want to use it as a reference. At this time, you need Shallow and Deep Copy when programming in Python .

What you need to know about Shallow and Deep Copy in Python Picture 1What you need to know about Shallow and Deep Copy in Python Picture 1

Python offers a number of effective approaches to data management. Understanding the concepts of shallow and deep copy is important when working with data structures such as nested lists, dictionaries, or custom objects.

Both shallow and deep copy allow you to copy data structures, but they work differently with nested data.

Use Shallow Copy

Shallow copy works by creating a copy of the original object's top structure. That means, if the original object contains nested objects, the copy will reference the same nested objects as the original object. In other words, making a shallow copy of an object copies its outermost structure, not any nested objects it may contain.

To implement a shallow copy in Python, you can use the copy module's copy() function or the .copy() method on the object.

Let's look at an example of working with a list of dictionaries in Python.

import copy main_list = [29, 49, ["Q", "R"]] shallow_copy = copy.copy(main_list) # Chỉnh sửa danh sách lồng nhau shallow_copy[2][0] = 99 main_list[2][1] = 100 print(f"The main list: {main_list}") print(f"The shallow copy list: {shallow_copy}")

In the code above, the main_list variable contains a list of integers and a nested list (nested object) containing letters. The copy function creates a copy of main_list, where the code contains another variable, shallow_copy .

Any changes you make on the shallow_copy nested list directly affect the main_list . These changes indicate that the shallow_copy 's nested or inner list is just a reference to the main_list , making the changes apply. used throughout main_list .

What you need to know about Shallow and Deep Copy in Python Picture 2What you need to know about Shallow and Deep Copy in Python Picture 2

Meanwhile, any changes made to external (integer) items in shallow_copy or main_list will only affect that version. External items are independent values ​​in their own right, not mere references.

import copy main_list = [29, 49, ["Q", "R"]] shallow_copy = copy.copy(main_list) # Chỉnh sửa các mục bên ngoài shallow_copy[0] = "M" main_list[1] = "N" print(f"The main list: {main_list}") print(f"The shallow copy list: {shallow_copy}")

This result proves that both the outer items of the list are independent of each other:

What you need to know about Shallow and Deep Copy in Python Picture 3What you need to know about Shallow and Deep Copy in Python Picture 3

The same idea applies when working with dictionaries.

dict1 = {'ten': 10, 'twenty': 20, 'double':{'thirty': 30, 'sixty': 60}} dict2 = dict1.copy() # Chỉnh sửa các phần tử bên trong và bên ngoài dict1['double']['thirty'] = 30.00 dict1['ten'] = 10.00 print(f"The main dictionary, {dict1}") print(f"The shallow copy dictionary, {dict2}")

Changes made to dict1's nested dictionary affect both dict1 and dict2. Meanwhile, changes to items outside of dict1 only affect it.

What you need to know about Shallow and Deep Copy in Python Picture 4What you need to know about Shallow and Deep Copy in Python Picture 4

Use Deep Copy

Instead of referencing the nested objects of the original copy, a Deep Copy creates a copy that is completely separate from the original object and its nested objects. Editing a deep copy will not affect the original object and vice versa. They are truly separate values.

To create a deep copy in Python, use the deepcopy() function of the copy module.

Consider an example of working with a list:

import copy main_list = [200, 300, ["I", "J"]] deep_copy = copy.deepcopy(main_list) # Chỉnh sửa danh sách bên trong và bên ngoài deep_copy[2][0] = "K" main_list[0] = 500 print(f"The main list: {main_list}") print(f"The deep copy list: {deep_copy}")

Here, the code implements a deep copy of main_list , creating an independent copy named deep_copy .

When editing nested lists or external items in deep_copy , your changes do not affect the original list and vice versa. This indicates that the nested list or outer elements are not shared between the two copies.

What you need to know about Shallow and Deep Copy in Python Picture 5What you need to know about Shallow and Deep Copy in Python Picture 5

Work with custom objects

You can create a custom object by defining a Python class and creating an instance of the class.

Here's an example of how to create a simple object from the Book class :

class Book: def __init__(self, title, authors, price): self.title = title self.authors = authors self.price = price def __str__(self): return f"Book(title='{self.title}', author='{self.authors}', price='{self.price}')"

Now, create both a shallow copy and a deep copy of an instance of the Book class using the copy module.

import copy # Tạo đối tượng Book book1 = Book("How to MakeUseOf Shallow Copy", ["Bobby Jack", "Princewill Inyang"], 1000) # Tạo một shallow copy book2 = copy.copy(book1) # Chỉnh sửa đối tượng gốc book1.authors.append("Yuvraj Chandra") book1.price = 50 # Kiểm tra đối tượng print(book1) print(book2)

As you can see, the shallow copy ( book2 ) is a new object, but it references the same internal object (list of authors) as the original object ( book1 ). Therefore, a change to the root's authors affects both instances ( book1 and book2 ), while a change to the outer item ( price ) affects only the root object ( book1 ).

In other words, a deep copy creates an independent copy of the original object, including copies of all objects within it.

# Tạo đối tượng Book book1 = Book("Why MakeUseOf Deep Copy?", ["Bobby Jack", "Yuvraj Chandra"], 5000) # Tạo một deep copy book2 = copy.deepcopy(book1) # Chỉnh sửa đối tượng gốc book1.authors.append("Princewill Inyang") book1.price = 60 # Kiểm tra các đối tượng print(book1) print(book2)

In this case, the deep copy ( book2 ) is a completely independent object, and editing the original object ( book1 ) has no effect on it.

What you need to know about Shallow and Deep Copy in Python Picture 6What you need to know about Shallow and Deep Copy in Python Picture 6

Use cases for shallow copy and deep copy

  1. Use shallow copy if you want to copy a complex object without creating new instances of the nested object. This method saves memory and runs faster than deep copy because it does not copy nested objects.
  2. Use shallow copy to create a snapshot of an object's state, while still sharing some underlying data between the original and copied object.
  3. Use deep copy if you want to edit a copy of an object without affecting the original object. This creates independent copies of the nested objects, ensuring any changes to the copy do not apply to the original object.
  4. Deep copy is important when you need independent copies of nested data structures, mainly when dealing with recursive or complex object hierarchies.

Above are the things you need to know about shallow and deep copy in Python . Hope the article is useful to you.

4.5 ★ | 2 Vote