Operations

Python Shallow Copy and Deep Copy (With Examples)

Do you ever wonder how one can simply fill out the info once and then copy it for convenience? We must copy existing data while programming. Copies are functions in Python that keep a skeleton of any code as a carbon copy in the library. This allows the programmer to recover any such code in the event of an error. To make a copy of a Python object, we usually use the = (assignment operator). Let’s go over the entire concept of making copies in Python. In this tutorial, we will look at how to copy an object in Python using the python shallow copy and python deep copy concepts.

Copy an Object in Python

When a user wishes to make changes without changing the original object, the copies come in handy. To work with mutable things, a user also prefers to make a copy.

The assignment operator (=) in Python, like in other programming languages, is used to copy or assign one variable to another. When we use the assignment (=) symbol to assign values, the assignment operator does not transfer the first variable’s actual values. This may appear to generate a new object, but it does not. It just creates a new variable that shares the old object’s reference.

Consider the following example: we establish a list called old_list and use the = operator to provide an object reference to new_list.

Example

                    

old_list = [1, 2, 3, 4, 5, 'a']
new_list = old_list

new_list[5] = 6

print('Old List:', old_list)
print('ID of Old List:', id(old_list))

print('New List:', new_list)
print('ID of New List:', id(new_list))

Output

                    

Old List: [1, 2, 3, 4, 5, 6]
ID of Old List: 140145128611200

New List: [1, 2, 3, 4, 5, 6]
ID of New List: 140145128611200

As shown in the result, both variables old_list and new_list have the same id, 140145128611200. So, if you alter any values in either the new_list or the old_list, the change is reflected in both.

Essentially, you may wish to leave the original numbers alone and simply change the new ones at times, or vice versa. There are two ways to make copies in Python:

  • Python Deep copy
  • Python Shallow Copy

Copy Module

To copy objects in Python, we have a distinct module named ‘copy.’ Python’s copy module is used for shallow and deep copy operations.

When modifications are required in the backup files but not in the main source code, a copy module is employed. This refers to the internal storage in the primary source file that can be altered from the coder’s perspective but not from the user’s perspective.

The Python copy module is a built-in function that preserves the original values while modifying only the copied variables or vice versa.

The copy module’s two main functions are:

  • copy.copy()
  • copy.deepcopy()

Example

                    

import copy

copy.copy(x)
copy.deepcopy(x)

In this case, copy() returns a shallow copy of x. The deepcopy(), on the other hand, returns a deep copy of x.

Shallow Copy

Python shallow copy is a feature that allows you to make a new object copy of an existing collection object. When we attempt to replicate a collection object with a shallow copy, it creates a new collection object and stores references to the original object’s elements.

When utilizing a Shallow Copy in Python, the coder generates a new object and recursively inserts all copies of objects into the original code. Similarly, we duplicate one object’s reference into another object. Any modifications made to the copy by the coder are reflected in the original copy of the code in the runtime.

In Python, the copy.copy(x) method is used to perform a shallow copy.

Example: Create a copy using shallow copy

                    

import copy

old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = copy.copy(old_list)

print('Old list:', old_list)
print('New list:', new_list)

Output

                    

Old list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In the above program, we generated a nested list and then shallow copied it with the copy() method. This means that it will generate a new, independent object with the same content. We print both the old list and the new list to confirm this. To ensure that the new list differs from the old list, we try to add a new nested object to the original and compare the results.

Example: Adding new value to old_list, using a shallow copy

                    

import copy

old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = copy.copy(old_list)

old_list.append([10, 11, 12])

print('Old list:', old_list)
print('New list:', new_list)

Output

                    

Old list: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In the previous program, we made a shallow copy of old_list. The new_list contains references to the original nested items that were kept in the old_list. Then we insert the new sublist i.e. [10, 11, 12] into the old_list. This newly added and created sublist was not copied into the new_list.

But, When you alter any nested items in the old_list, the changes are reflected in the new_list.

Example: Adding new nested object using Shallow copy

                    

import copy

old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = copy.copy(old_list)

old_list[0][1] = 'XYZ'

print('Old list:', old_list)
print('New list:', new_list)

Output

                    

Old list: [[1, 'XYZ', 3], [4, 5, 6], [7, 8, 9]]
New list: [[1, 'XYZ', 3], [4, 5, 6], [7, 8, 9]]

In the above program, we changed old list to old list[0][1] = ‘XYZ’. Both old list and new list sublists at index [0][1] were updated. This is due to the fact that both lists include references to the same hierarchical items. This will not happen if we add/update a single indexed element of the old list. Only the list which we have single indexed updated will get updated and that will not affect the other list.

Deep Copy

A Python deep copy produces a new object and recursively adds copies of nested objects from the original elements. In other words, it makes a new duplicate of the new object that recursively adds copies of the items or values in the original list. If we make modifications to the copy object, the changes are not reflected in the original objects. This is done in Python with the ‘deepcopy()‘ method. The Python deep copy makes an independent copy of the original item as well as all of its nested objects.

Example: Copying a list using deepcopy()

                    

import copy

old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = copy.deepcopy(old_list)

print('Old list:', old_list)
print('New list:', new_list)

Output

                    

Old list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In the above program, we utilize the deepcopy() function to make a copy that is comparable to the original. If you make modifications to any nested objects in the original object old_list, the copy new_list will not alter.

Example: Adding a new nested object in the list using Deep copy

                    

import copy

old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = copy.deepcopy(old_list)

old_list[0][1] = 'XYZ'

print('Old list:', old_list)
print('New list:', new_list)

Output

                    

Old list: [[1, 'XYZ', 3], [4, 5, 6], [7, 8, 9]]
New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

When we set a new value to old_list in the above program, we can observe that only the old_list is affected. This indicates that both the old_list and the new_list are self-contained. This is due to the fact that the old_list was recursively duplicated, as were all of its nested items.

Frequently Asked Questions

Q1. What is a deep copy in Python?

A Python deep copy produces a new object and recursively adds copies of nested objects from the original elements. In other words, it makes a new duplicate of the new object that recursively adds copies of the items or values in the original list. If we make modifications to the copy object, the changes are not reflected in the original objects. This is done in Python with the ‘deepcopy()‘ method. The Python deep copy makes an independent copy of the original item as well as all of its nested objects.

Q2. What is the difference between shallow copy and deep copy in Python?

There is a significant difference between shallow and deep copying for compound objects such as lists, dicts, and sets:

  • Python Shallow Copy – A shallow copy is created by creating a new collection object and then populating it with references to the original’s child objects. A shallow duplicate, in essence, is only one level deep. Because the copying operation does not recurse, no copies of the child objects are created.
  • Python Deep Copy – The copying process becomes recursive with a deep copy. It entails first creating a new collection object and then recursively populating it with copies of the original’s child objects. Copying an item in this manner traverses the entire object tree, resulting in a fully independent clone of the original object and all of its children.

Another major difference is that the Python deep copy does not reflect any changes to the new/copied object in the original object, whereas the shallow copy does in the run time code.

Q3. How do you create a Python deep copy?

To create a Python deep copy, we make use of the deepcopy() function. For example,

                    

import copy

old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = copy.deepcopy(old_list)

print('Old list:', old_list)
print('New list:', new_list)

Output

                    

Old list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
New list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In the above program, we utilize the deepcopy() function to make a copy that is comparable to the original. If you make modifications to any nested objects in the original object old_list, the copy new_list will not alter.

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Browse

Operations
  • Python Shallow Copy and Deep Copy (With Examples)

Leave a Reply

Your email address will not be published. Required fields are marked *

Browse

Operations
  • Python Shallow Copy and Deep Copy (With Examples)

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.