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 .
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 .
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:
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.
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.
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.
Use cases for shallow copy and deep copy
- 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.
- Use shallow copy to create a snapshot of an object's state, while still sharing some underlying data between the original and copied object.
- 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.
- 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.
You should read it
- What is Python? Why choose Python?
- 5 choose the best Python IDE for you
- Object-oriented programming in Python
- How to Start Programming in Python
- Multiple choice quiz about Python - Part 3
- Multiple choice quiz about Python - Part 1
- Multiple choice test on Python - Part 11
- Programming blockchain part 3: Python programming language
May be interested
- What is Python? Why choose Python?python is a powerful, high-level, object-oriented programming language, created by guido van rossum. python is easy to learn and emerging as one of the best introductory programming languages for people who are first exposed to programming languages.
- Module time in Pythonpython has a time module used to handle time-related tasks. tipsmake.com will work with you to find out the details and functions related to the time specified in this module. let's follow it!
- Python data type: string, number, list, tuple, set and dictionaryin this section, you'll learn how to use python as a computer, grasp python's data types and take the first step towards python programming.
- How to install Python on Windows, macOS, Linuxto get started with python, you first need to install python on the computer you are using, be it windows, macos or linux. below is a guide to installing python on your computer, specific to each operating system.
- How to set up Python to program on WSLget started with cross-platform python programming by setting up python on the windows subsystem for linux. here's how to set up python for wsl programming.
- Multiple choice quiz about Python - Part 4continue python's thematic quiz, part 4 goes back to the topic core data type - standard data types in python. let's try with quantrimang to try the 10 questions below.
- How to use Closure in Pythonin this article, tipsmake.com will work with you to learn about closure in python, how to define a closure and why you should use it. let's go find the answer!
- Functions in Pythonwhat is python function? how is the syntax, components, and function types in python? how to create functions in python? these questions will be answered in the python lesson below.
- How to use GPT-3 with Pythonfeel free to use cool gpt-3 technology with your own python scripts using openai's handy api. here are details on how to use gpt-3 with python.
- Multiple choice quiz about Python - Part 7following the previous test set, part 7 continues with the topic built-in functions in python. let's try with quantrimang to try the 10 questions below.