Shallow Copy Vs Deep Copy in Python | True Copy of List in Python | Deep Copy of List in Python

preview_player
Показать описание
In this video you will learn about shallow copy and deep copy in python.

Copy module
In python copy module is used to copy the objects. We have following two methods before Lets see why we need copy module.
when we write L1 = L2 (here both are Lists) it means it just alias of same memory location means L1 and L2 are two names of same List. so when we changes one list , changes reflect in other list. for example
L1=[12,45,10,89]
L2=L1
print(L1) # [12, 45, 10, 89]
print(L2) # [12, 45, 10, 89]

L1[1]=50 # change in List L1

print(L1) #[12, 50, 10, 89]
print(L2) #[12, 50, 10, 89] Both lists are changed

Output :
[12, 45, 10, 89]
[12, 45, 10, 89]
[12, 50, 10, 89]
[12, 50, 10, 89]

So we need copy module. Two types are :

1. copy() : It creates the shallow copy.
2. deepcopy(): It creates the deep copy.
Shallow copy vs Deep copy in python.
Shallow copy : A shallow copy creates a new object which stores the reference of the original object, but a shallow copy doesn't create a new copy of nested objects, instead it just copies the reference of nested objects. We use copy() function of copy module.
In python you can't simply use the = to copy something from one variable/object to another variable/object. To truly copy something you need to make use of the shallow copy or deep copy, this python tutorial shows you why.
In this video you will learn about shallow copy and deep copy in python.
Рекомендации по теме
Комментарии
Автор

Excellent explaination deep copy and shallow

nirmaldevi
Автор

Very good explanation of deep copy and shallow copy

subhashlamba
Автор

Very good explanation of deep copy and shallow copy

Rishta_hi_Rishta_