Cyberithub

Shallow and Deep: Types of Copy in Python with Best Examples

Advertisements

In this tutorial, we will see about shallow and deep copy used in Python with Best Examples. We have already discussed about the famous OOPs concept like Inheritance, Polymorphism and Data Encapsulation in Python in our earlier tutorials. So now let's move ahead and talk about another interesting concept in Python.

Objects are not normally copied. When we write:
a = b

we now have two references to the same underlying object. If b is a list, both a and b are references to the same, mutable list. As we might be aware from the concepts of variable in Python, a change to the a variable changes the list object that both a and b refer to. More on Python Cookbook.

Most of the time, this is the behavior we want. There are rare situations in which we want to actually have two independent objects created from one original object. There are two ways to break the connection that exists when two variables are references to the same underlying object:-

  • Making a shallow copy of the structure
  • Making a deep copy of the structure

 

Shallow and Deep: Types of Copy in Python with Best Examples

Shallow and Deep: Types of Copy in Python

Also Read: 30 Important Python Data Structures Interview Questions and Answers

In Python, when we use assignment('=') operator in a statement, it doesn't copy the object instead it creates a link between original and new object. Such statements only create a reference to original object. There comes requirement when we want to copy the object and do modification on it without impacting the original object and vice versa. copy concept allows user to perform such operations. There are 2 types of copy in python. They are:

  • Shallow copy
  • Deep copy
mylist= [2,3,7]
copylist= mylist
mydic= {'A':1, 'B':2}

copydic= mydic
myset= {4,'s', 8}
copyset= myset

print(mylist)
print("Id of mylist:", id(mylist))
print(copylist)
print ("Id of copylist:", id(copylist))

Program Output

[root@localhost ~]# python example.py
[2, 3, 7]
('Id of mylist:', 140141239558224)
[2, 3, 7]
('Id of copylist:', 140141239558224)

Both the object in above example will refer to same memory address. Hence changes made by any will get reflected for other as well.

mylist= [2,3,7]

copylist= mylist
copylist.append('r')

print(mylist)
print(copylist)

Program Output

[root@localhost ~]# python example.py
[2, 3, 7, 'r']
[2, 3, 7, 'r']

1. Shallow copy

It is a process where a new object is created which stores the reference of original object. It doesn't create the copy of nested object. Hence, nested recurse doesn’t work in shallow copy. We use copy module to perform shallow copy in python. The copy module supplies a copy function to create and return a copy of many types of objects. Normal copies, such as list(x) for a list x and copy.copy(x), are known as shallow copies: when x has references to other objects (either as items or as attributes), a normal (shallow) copy of x has distinct references to the same objects. More on Python in a Nutshell.

Program Example

import copy

mylist= [2,3,7]
copylist= copy.copy(mylist)

print("Values before making changes:")
print(mylist)
print(copylist)

copylist[1] = 5

print("Values after making chnages:")
print(mylist)
print(copylist)

Program Output

[root@localhost ~]# python example.py
Values before making changes:
[2, 3, 7]
[2, 3, 7]
Values after making chnages:
[2, 3, 7]
[2, 5, 7]

2. Deep copy

It is a process where copy happens recursively in referenced object. Changes done on referenced object would not impact the original object. Sometimes, however, you need a deep copy, where referenced objects are deep-copied recursively. Fortunately, this need is rare, since a deep copy can take a lot of memory and time. The copy module supplies a deepcopy function to create and return a deep copy.

Program Example

import copy

mylist= [2,3,7]
copylist= copy.deepcopy(mylist)

print("Values before making changes:")
print(mylist)
print(copylist)

copylist.append('s')

print("Values after making chnages:")
print(mylist)
print(copylist)

Program Output

[root@localhost ~]# python example.py
Values before making changes:
[2, 3, 7]
[2, 3, 7]
Values after making chnages:
[2, 3, 7]
[2, 3, 7, 's']

Conclusion

In this tutorial we have learned about the use of Copy Module along with its two different types used in Python: Shallow and Deep Copy. We have also understood and seen the usage of Shallow and Deep copy in Python with Examples.

Leave a Comment