Python Deep Copy and Shallow Copy

We use collections to initialise the data in shallow copy and deep copy. Collections of elements are mutable. We will be learning about shallow and deep copy in Python. We will be also discussing about the =, copy() and deepcopy() operations in this article. Let’s start.

Python Equal to Operation

The equal to operation creates a copy of the object in python.

Consider two lists:

lst1=[1,2,3,4]
lst2=lst1

The equal to operation copies elements of the lst1 into lst 2. So when we execute the code and print lst1 and lst2, we get the same output for both the lists:

[1, 2, 3, 4]

[1, 2, 3, 4]

Suppose we make changes to an index element of the lst1. Then the same changes will be reflected in the index element of the lst1.

lst1[1] = 1000

The above code will print 1000 for both the index element 1 of both the lists. The reason is the lst1 creates this collection of items in a memory location and both the variables refer to the same memory location. Therefore when you make changes to the first lst1 change will be seen in the lst2.

Attributes of copy module in Python

1. copy.copy(x)

Gives the shallow copy of x

2. copy.deepcopy(x)

Gives the deep copy of x

3.  Exception copy.error

If it encounters, it returns an exception

Shallow copy creates another file inside the text file to store new information. It never manipulates the original code. Changes are made only to the new copied file. Python shallow copy and deep copy are easy to learn but the only difficulty is which copy to use in what situations.

Let us look at each one of them in detail.

Example for python copy

lst1=[1,2,3],[‘#’,’*’,’-’]
lst2=[0,9,8,7]
print(lst1)

Output

([1, 2, 3], [‘#’, ‘*’, ‘-‘])
** Process exited – Return Code: 0 **
Press Enter to exit terminal

Python shallow copy module

We use a copy model when we want to make changes in the backup files but we do not want to make any changes in the main source code. Suppose we want to make changes to the internal storage from the coders view but we do not want to make any changes to the users view in the main source file.

Syntax for shallow copy in Python

import copy
copy.copy(variable_name)

shallow copy python

Consider the piece of code

lst1=[1, 2, 3, 4]
lst2=lst1.copy()

This code copies all the elements of the lst1 int lst2 and the output will be the same for both of the lists.

This is a type of shallow copy. The copy() makes a different memory location instead of referring to the same memory location. So changes in one loft do not directly affect changes in another list.

Consider nested lists:

lst1=[[1,2,3,4],[5,6,7,8]]
lst2.lst1.copy()

When we can consider objects in items such as in nested lists, when we try to change values in this situation the value is copied in both lists because the variable refers to the same object inside the nested list. For example:

lst[1][0]=1000

Output:

[[1,2,3,4],[5,1000,7,8]]

Now if we use the append() operation on one of the lists then the effect will not reflect on the other list in the case of shallow copy. So, in shallow copy, the item will not be copied but the changes to objects inside the item will be copied.

Shallow copy creates a new object and puts references into the objects of the original. Basically, any changes made to the variables in the first copy can be seen in the second one as they both point to the same object.

Example of shallow copy:

import copy

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

Output:

(1, 0, [7, 9], 6)
** Process exited – Return Code: 0 **
Press Enter to exit terminal

Python Dictionaries shallow copy

This is the effective method that offers interface in the code.

import copy

a = {1: [1,2,3]}
b = a.copy()
print(a)
print(b)

a[1].append(4)
print(a)
print(b)

Output:

{1: [1, 2, 3]}
{1: [1, 2, 3]}
{1: [1, 2, 3, 4]}
{1: [1, 2, 3, 4]}** Process exited – Return Code: 0 **
Press Enter to exit terminal

Python Deep copy()

Python Deep copy creates a new object. We insert copies instead of direct references to the objects so changes made to one variable do not reflect to another variable copy as they both point to DIFFERENT objects in the case of deep copy.

Syntax for Python deep copy

import copy
copy.deepcopy(variable_name)

Example of deep copy in Python

import copy
a = [10, 20, 30]
b = copy.deepcopy(a)
a[1] = 70   # value of 'b' does NOT change because it is ANOTHER object
print("Deep copy: ", b)

Output

Deep copy: [10, 20, 30]
** Process exited – Return Code: 0 **
Press Enter to exit terminal

Disadvantages of deep copy in Python

1. Deep copy is much slower to implement than shallow copy.

2. Deep copy may copy too much consider the data that we want to share among different copies.

3. Using deep copy for recursive objects more often leads to a recursive loop.

We have to use the library “copy” in order to use the deep copy operation. Consider the code:

Import copy
lst1=[1,2,3,4]
lst2=copy.deepcopy(lst1)

Now suppose we make changes in the lst1

lst2[1]=1000

Output:

[1,1000,3,4]

The changes cannot be seen in lst1.

In a single dimension list, shallow copy is similar to nested copy

lst1=[[1,2,3],[4,5,6],[7,8,9]]
lst2=copy.deepcopy(lst1)
lst2[1][0]=1000

The above change is not done in lst1. In deep copy there is a separate memory location for every operation we perform. This is the difference between shallow and deep copy.

deep copy python

Difference between shallow copy and deep copy in python

1. Shallow copies do not clone child objects. Hence the copy is not fully independent of the actual object.

2. A deep copy on the other hand recursively clones a child object. The clone is fully independent of the original object but is is however slower to implement deep copy.

shallow copy and deep copy python

Copying arbitrary objects in python

The copy attributes can also be used to copy custom classes and other random objects. The copy.copy() and copy.deepcopy() that we have seen above can also be used to duplicate any objects.

Example:

import copy  
class Funct_New:  
    def __init__(self, x, y):  
        self.x = x  
        self.y = y  
  
    def __repr__(self):  
      return 'Funct_new(%r, %r)' % (self.x, self.y)  
  
a = Funct_New(30, 33)  
b = copy.copy(a)  
  
print(a)  
print(b)  
  
print(a is b)  
print(b is a)  

Output:

Funct_new(30, 33)
Funct_new(30, 33)
False
False
** Process exited – Return Code: 0 **
Press Enter to exit terminal

Conclusion

So we learn about the major difference between equal to operation, shallow copy and deep copy in python. We look at the changes it makes in single and multidimensional lists. We hope our explanation was easy to understand.

If you are Happy with PythonGeeks, do not forget to make us happy with your positive feedback on Google | Facebook


Leave a Reply

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