When working in Python, assignment operators and statements don’t create object copies. Instead, they make a binding between names and targeted objects.
In this post, we will learn Python copy concepts with the help of shallow copy and deep copy in Python. We’ll explain each type of copy and how to write it. We’ll also give you a few example Python scripts to get you started. So whether you’re new to Python or need a refresher, this article is for you.
Table of Contents
How to Copy an Object in Python?
In Python, we use the assignment operator (=) to create an object’s copy. We might think this creates a new object, but it only initiates a new variable referring to the original object.
In Python, there are two ways of copying an object in Python.
1. Shallow Copy
2. Deep Copy
Copying data between two objects is a common task that requires the use of shallow copy and deep copy. Shallow copying takes the simplest form, where only the basic attributes of an object are copied; deep copying goes one step further and includes allocating new memory space for the duplicate objects.
The following code snippet explains how Python copy works.
list_old = [[2, 4, 6], [8, 10, 12], ['a','b','c']] list_new = list_old list_new = 2 print('The Old List:', list_old) print('ID of Old List:', id(list_old)) print('The New List:', list_new) print('ID of New List:', id(list_new))
Both new and old lists share the same id number. This means changing in either of them will reflect changes in both new list and old list.
For the above two types, we use the ‘copy’ module. So let’s learn about Python copy types in detail.
1. Shallow Copy
Python Shallow Copy is used to create a new object that stores the reference of the original object. This way, there is no copy of nested objects, but only the reference of nested objects is copied.
Only the properties referenced by name will be copied over when you perform a shallow copy operation. This means that if you have an instance of “Student” and want to create another “Student” using the same properties but with different values for some fields, then a shallow copy would be ideal because nothing else would be modified.
Let’s learn with the following example.
import copy list_old = [1,['a','b'], 3, 5] list_new = copy.copy(list_old) print ("Before SHALLOW COPY:") for x in range(0,len(list_old)): print (list_old[x],end=" ") print("\r") list_new = 'h' print ("After SHALLOW COPY:") for x in range(0,len( list_old)): print (list_old[x],end=" ")
2. Deep Copy
Python deep copy is used to create a new object, adding the copies of nested objects from original elements in a recursive manner.
If you want to make a deep copy operation, which preserves not just attributes specified in code but also class variables (and even instances, methods(), enumerable(), files(), etc.). Then first need to assign some additional memory space to hold your copies before doing anything else. For example, let’s say we have an instance of Student called stud1, and we want STUDENT_DEEP=True, so our clone will include all its inheritance and its own state. (In Python 3, this can also be done automatically with set default.)
Check the following example to understand better.
import copy list_old = [0, ['g','h'], 4] list_new = copy.deepcopy(list_old) print ("Before DEEP COPY: ") for x in range(0,len(list_old)): print (list_old[x],end=" ") print("\r") list_new = 'R' print ("After Deep Copy: ") for x in range(0,len( list_old)): print (list_new[x],end=" ") print("\r") print ("Original List before Deep Copy: ") for x in range(0,len( list_old)): print (list_old[x],end=" ")
Are there other benefits to using shallow and deep copy in Python?
Shallow copy allows you to quickly write code that is easy to read and understand, while deep copy helps you create robust and testable code.
What are some best practices when working with copies of objects in Python?
Copying objects in Python can be tricky if you’re not careful. This is because the copy constructor is an explicit function that always creates a new object. Additionally, when working with mutable types like lists and dictionaries, copying objects can result in unexpected consequences. To avoid this, use the deep copy module to create a shallow copy of an object without altering its contents. This will allow you to reuse instances of the original object without worrying about modifications or deletions happening inadvertently.
What are some common uses for shallow copy and deep copy in Python?
Shallow copying is beneficial when creating a quick duplicate for reference or when space is limited. Deep copying may be more appropriate if sensitive values are involved or if you plan on using the copied object in another context.
Copy concepts in Python can be a little confusing. That’s why this post was designed to help you understand copy in Python with the help of shallow copy and deep copy. We have provided you with an example script to help you get started. I hope this article was helpful.