Python Deep Copy and Shallow Copy with Examples

Do you ever wonder how one can simply fill data once and then merely make its copy to prefer ease? Not possible for a textbook, of course, but Python has its own magic, and yes, it does this for his coder.

How?

Copies in python are such functions that maintain a skeleton of any code as a carbon copy in the library. This helps the coder to retrieve any such code in case of any error.

There are basically two types of copies: shallow copy and deep copy. But there lies a major difference in the working of both, what is it and where are they used?

Everything is explained in the article. So, let’s get started.

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

Python Copy Module

A copy module is used when some changes are needed in the backup files but not in the main source code. This refers to the internal storage that can be manipulated from the coder’s point of view but not the user’s point of view in the main source file.

Some of the attributes are:

1. copy.copy(x)
It returns a shallow copy of x.

2. copy.deepcopy(x)
It returns a deep copy of x.

3. exception copy.error
It returns an exception if needed.

A shallow copy creates a separate file within the text file which stores information. The original code is never manipulated, but changes can be surely made in the new copied file.

The basic idea of shallow and deep copy constructs a few debugging problems within the text.

Recursive objects face problems in shallow copy, but this is resolved with deep copy. This also intends the deep copy to work more efficiently than the shallow copies in runtime.

This module copies functions and classes both deep and shallow by returning the original object unchanged in the main code itself.

It is generally also compatible with the way these are treated by the pickle module in any code specific run time in python.

How to Perform Shallow and Deep Copy in Python?

Shallow Copy Syntax in Python:

import copy
copy.copy(objectvariable_name)

Deep Copy Syntax in Python:

import copy
copy.deepcopy(objectvariable_name)

Python Copy Example

#method to print the list
thisistech= [1, 2, 3],['#',"*","-"]
newtech=[0,9,8,7]
#the functions returns as it is 
print('Old List:', thisistech)

Output:

Old List: ([1, 2, 3], [‘#’, ‘*’, ‘-‘])

Python Deep Copy

While a deep copy in Python creates a new object, it also inserts the new object in the original object by efficiently copying it. Similarly it copies an object into another object within the main code. This basically signifies that the required changes in the main dictionary are well automated in the main library also.

Python Deep Copy Example

>>> import copy
>>> list1=[1,0,[7,9],6]
>>> list2=copy.deepcopy(list1) #Making a deep copy
>>>print( list1)

Output:

[1, 0, [7, 9], 6]

Addition of Nested Loop: Nested loop, unlike in lists, can be added in the deep copy. The shallow copy doesn’t support the reframe work of nested loops in new versions of python. Though it can be used in the old versions.

Code:

l=int(input("enter number"))
 
 
old__list = [[1, 1, 1], [2, 2, 2], [5, 5, 5]]
 
print("Old list:", old__list)

Output:

enter number 67
Old list: [[1, 1, 1], [2, 2, 2], [5, 5, 5]]

Issues With Python Deep Copy

While it is possible that recursive objects cause a recursive loop; these are the compound objects that directly or indirectly reference themselves. And it is possible that a deep copy may copy too much.
To deal with these problems, deepcopy() also :

1. Deep copy parses the newly added information in its file. This helps the coder to identify new files easily in the code.
2. Deep copy does not allow the coder to overwrite in the code, but builds a copy of the shallow code using internal files.
3. Deep copy, as well as shallow copy, is made by parsing a list or tuple together in the runtime.

Regardless of this, the copy module uses the registered pickle functions from the copyreg module within the code itself, it does not refer to the original code.

Copying Arbitrary Python Objects: Python arbitrary objects can be compiled in a list easily. It can be done by adding the elements recursively in the runtime for any defined list.

Code:

class Point:
    def __init__(self, A, B):
        self.P = A
        self.Q= B


A = int(input("a")

Output:

>>> a

Python Shallow Copy

While using a Shallow Copy in Python, the coder creates a new object in which he/she recursively puts all the copies of objects into the original code. Similarly, we copy a reference of an object into another object also. Any changes the coder makes to the copy do reflect in the original copy of code in the runtime.

Python Shallow Copy Example:

>>>import copy
list=1,0,[7,9],6
list_2=copy.copy(list) #Making a shallow copy
print(list)

Output:

(1, 0, [7, 9], 6)
>>>

Shallow Copying Dictionaries: This is a general method for providing an interface in the main source code.

Code:

>>> dict_1={'a':0,'b':2,'c':[0,2,3]}
 
 
dict_2=dict_1.copy()
 
dict_2['c'].append(9)
dict_1={"a": 0}
print(dict_2)
 

Output:

{‘a’: 0, ‘b’: 2, ‘c’: [0, 2, 3, 9]}
>>>

Adding any element as [0,0] to the list, using shallow copy: This method adds elements by extracting from one list to another one by one.

Code:

import copy
old_list0 = [[1,1], [2,2]]
new_list1 = copy.copy(old_list0)
old_list0.append([0,0])
print("New list:", new_list1)

Output:

New list: [[1,1], [2, 2,]]

Adding new nested objects using Shallow copy: The objects are oriented from the list, and then extracted in the copies of the source code.

Code:

import copy
l=(“enter number”)
li=[]
l.append(li)
print(li)
listone = [[1, 1, 1], [2, 2]]
n=(“enter number”)
ni=[]
n.append(ni)
print(ni)
new_list = copy.copy(old_list)
oldlist0[1][1] = 'pq'
print("New list:", new_list1)

Output:

Error

#no new obj to append

Difference Between Python Deep Copy and Shallow Copy

Having discussed what shallow and deep copies are and why we create copies, it’s time to learn about the difference between them. Actually, there are just two core differences and they’re linked with each other:

  1. Deep copy stores copies of an absolute object’s values, whereas a shallow copy stores references which are absolute to the original memory address in the runtime code.
  2. Deep copy doesn’t reflect any change made to the new/copied object in the original object; but shallow copy does the same in the run time code.

Example for Python Deep Copy vs Shallow Copy

Code 1:

import copy
result_p = [100,90], [30,40] 
result_q = [10,90], [340] 
 
 
print("Original List: ")
print(result_p)
print("Deep Copy:")
print(result_q)

Output:

Original List:
([100, 90], [30, 40])
Deep Copy:
([10, 90], [340])
>>>

Code 2:

import copy
result_p = [[85, 82], [ 88, 90]] 
 
 
print("Original List: ")
print(result_p)

Output:

Original List:
[[85, 82], [88, 90]]
>>>

Conclusion

As the article concludes, we get to know about the 2 different types of copies that python serves us and their correct usage. Copying is easy, but the assessment of where to do it is a tough task.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.