×

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

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Get index of element in array in python

Index : Index is a number where the element is located in the given list. In other words it is the position of the element in the list. Index can also...

4 minutes read.

Python str() function

Python str() function The str() function in Python converts the specified value into a string. Syntax class str(object='')           or class str(object=b'', encoding='utf-8', errors='strict') Parameter object:  This parameter represents any object to convert the given...

1 minute read.

Python Multithreading

In python, we can implement multithreading. In this tutorial, we will understand the basics of implementing multithreading in a python programming language. Multithreading is just like multiprocessing. We use it...

4 minutes read.

How to add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes read.

How to Install PIP In Python

How to Install PIP In Python The libraries for Python have made our work easier than we expected. From a simple addition of two numbers to applying algorithms on the big...

4 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

Application to Search Installed Application using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python Algorithms

A quote goes, "A goal without a plan is just a wish." To achieve anything in life, we can't simply go for it without making a plan and sticking to...

4 minutes read.

How To Take Multiple Inputs In Python

In C language, we make use of the scanf() function to obtain the values from the user and store it in the variable. Coming to the Python language, we use the...

5 minutes read.

Captcha Code in Python with Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Cx_Oracle Python with Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

ComboBox in Python

Python includes several graphical user interface (GUI) libraries, including PyQT, Tkinter, Kivy, WxPython, and PySide. Tkinter is the most commonly used GUI module in Python because it is simple and...

2 minutes read.

How to Reverse a number in Python?

In Python, conditional statements can be combined with the list() method, slice() method, recursion() method, and other predefined techniques to generate reverse logical functions. The reverse() method is the most...

7 minutes read.

Iterators in Python

Introduction In Python, an iterator is defined as an object that enables traversing through all the values of a collection. It contains the countable number of values. The iterator is utilized to...

4 minutes read.

Python Built-in Functions

Python Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. The Python built- in functions are as follow: Methods Explaining abs() The abs() function returns...

6 minutes read.