×

Python Deep Copy and Shallow Copy

Assignment statements in Python create bindings between a target and an object, not copies of them. The = operator only makes a new variable that shares the reference to the original object when it is used. The Python copy module can be used to make "true copies" or "clones" of these objects.

In essence, we might occasionally only want to change the new values and leave the original values alone. There are two techniques for making copies in Python:

  • Deep Copy
  • Shallow Copy

We employ the copy module to make these copies functional.

However, this approach only generates shallow copies and is ineffective for custom objects. There is a significant distinction between shallow and deep copying for compound objects like dicts, lists and sets:

Creating a new selection object and then inhabiting it with references to the child items found in the original is known as a "shallow copy." A shallow copy is essentially one level deep. Since the copying procedure does not recurse, copies of the child objects themselves will not be produced.

The copying procedure is iterative when using a deep copy. It entails first building a fresh collection object, which is then recursively filled with duplicates of the original collection object's children. By copying an object in this way, the original object and all of its children become completely independent clones.

Shallow Copy in Python:

A shallow copy builds a brand-new collection object and thereafter populates it with references to the child objects located in the original. It then references the objects contained in the original within the new compound object that it creates. The copying procedure doesn't recurse, so the child objects themselves won't be duplicated. When an object is copied, its reference is incorporated into another object. In other words, any modifications made to a copy of an object will be reflected in the original object. The "copy()" function in Python is used to carry out this.

Example:

The fact that another list was impacted by the change made in this example shows that the list was only superficially copied. Important Information The distinction between deep and shallow copying only applies to compound objects (i.e., items like lists or instances of classes that contain other items):

To the greatest extent possible, a shallow copy creates a new compound object and then references the objects found in the original within it.

A deep copy creates a new compound object before inserting copies of the objects found in the original into it in a recursive manner.

Sample Code:

# importing "copy" for copy operations
import copy


# initializing list 1
list1 = [1, 2, [3,5], 4]


# using shallow copy to copy
list2 = copy.copy(list1)


# original elements of list
print ("The original elements before shallow copying")
for i in range(0,len(list1)):
	print (list1[i],end=" ")


print("\r")


# adding a new list element
list2[2][0] = 7


# determining whether a change is reflected
print ("The original elements after shallow copying")
for i in range(0,len( list1)):
	print (list1[i],end=" ")

Output:

Python Deep Copy and Shallow Copy

Deep Copy in Python:

In a deep copy, a new compound object is first created, and then copies of the components found in the original are recursively inserted into it. It entails creating a new collection object first, then populating it recursively with copies of the child objects discovered in the original. When using deep copy, an object is duplicated inside of another object. In other words, any modifications made to a copy of the object that do not affect the original object.

Example:

The fact that other lists were unaffected by the change made to the list in the example above shows that the list is heavily copied.

Sample Code:

# importing "copy" for copy operations
import copy
# initializing list 1
list1 = [1, 2, [3,5], 4]


# using deepcopy to deep copy
list2 = copy.deepcopy(list1)


# original elements of list
print ("The original elements before deep copying")
for i in range(0,len(list1)):
	print (list1[i],end=" ")


print("\r")


# adding a new list element
list2[2][0] = 7


print ("The new list of elements after deep copying ")
for i in range(0,len( list1)):
	print (list2[i],end=" ")


print("\r")


#Original list does not reflect the change.
# since it's a deep copy
print ("The original elements after deep copying")
for i in range(0,len( list1)):
	print (list1[i],end=" ")

Output:

Python Deep Copy and Shallow Copy

Related Topics

Character Set in Python

A collection of legal characters that will recognize by a programming language known as a Character set. Taking python programming language as an instance. The set of characters supported by the...

6 minutes read.

Python Dictionary update() method

Python Dictionary update() method The dictionary.update() method in Python inserts the specified items to the dictionary. Syntax dictionary.update(iterable) Parameter iterable- This parameter represents a dictionary or an iterable object with key value pairs, that will...

1 minute read.

Convert uppercase to lowercase in Python

Python String lower() By using the built-in string lower() method, all the uppercase characters can be converted into lowercase characters in a string, The lowercased string from the given string is returned...

1 minute read.

Python Multiprocessing Processor

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Python program for perfect number

Python program for perfect number Before writing any program for a given problem, we have to understand the problem for which we are creating a solution program. So, let's understand what...

2 minutes read.

How to uninstall python

To un-install Python, we need to follow different procedures in different operating systems. In this article, we will discuss the un-installation process of Python in Windows, Mac, and Linux operating...

4 minutes read.

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

Anaconda in Python 3

What is Anaconda in Python 3? Anaconda is an open-source package combining Python and R programming languages used for data analytics and processing data. It consists of a huge number of...

4 minutes read.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

Math Module in Python

In this article, you are going to learn everything in detail about the “ math “ module in Python. We can normally work with general operations using python without importing or...

16 minutes read.

Python program to find whether a given number is even or odd

Python program to find whether a given number is even or odd A number is said to be even if any number is completely divisible by 2, which means there is...

1 minute read.

Python List insert() method

Python List insert() method The list.insert () method in Python inserts an item at the specified position. Syntax list.insert(i, x) Parameter i: This parameter represents a number specifying the position to insert the given value. x: This parameter signifies...

1 minute read.

Python Queue

Python Queue There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for...

7 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Python round() function

Python round() function The round() function in Python returns a number rounded to ‘ndigits’ precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input. Syntax round(number[, ndigits]) Parameter Number: This parameter represents the...

1 minute read.

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

Python Setup guide and installation

Python Installation guide Step by Step Python is widely used high-level programming language. The first version of Python was launched in 1991. Since then, Python has been gaining popularity. It is considered as...

4 minutes read.

Python String rstrip() method

Python String rstrip() method The string.rstrip() method in Python returns a copy of the string with trailing characters removed. Syntax string.rstrip([chars]) Parameter chars:  This argument represents a string specifying the set of characters to be...

1 minute read.

Python PyMOTW

The cmd module comprises one class of the general public, Cmd, meant for command processors such interactive shells and other command interpreters as a foundation class. It utilises readline as...

3 minutes read.

Python Data Visualization

In this tutorial, we will understand what data visualization means in python. Further, we will see different methods of visualizing data in python. Data visualization In a non-technical language, it is a...

4 minutes read.