Copy Techniques in Python
Copy Techniques in Python
1. Shallow Copy
2. Deep Copy
-----------------------------------------------------------------------------------
------------------------------------
1. Shallow Copy
-----------------------------------------------------------------------------------
------------------------------------
=>The Properties of Shallow Copy are
a) Initial Content of Both the Objects are SAME
b) The Memory Address of Both the Objects are DIFFERENT
c) The Modifications are Indepedent ( Whatever the changes we do on one
object,
Which are not reflected to another object )
=>To Implement the Shallow Copy Technique, we use copy().
Syntax: object2=object1.copy()
Examples:
-------------------------
>>> l1=[10,"Rossum",23.45]
>>> print(l1,id(l1))------------[10, 'Rossum', 23.45] 1996956062656
>>> l2=l1.copy() # Shallow Copy
>>> print(l2,id(l2))------------[10, 'Rossum', 23.45] 1996959406400
>>> l1.append("Python")
>>> l2.insert(1,"Nether")
>>> print(l1,id(l1))-----------[10, 'Rossum', 23.45, 'Python'] 1996956062656
>>> print(l2,id(l2))-----------[10, 'Nether', 'Rossum', 23.45] 1996959406400
-----------------------------------------------------------------------------------
------------------------------------
2. Deep Copy
-----------------------------------------------------------------------------------
------------------------------------
=>The Properties of Deep Copy are
a) Initial Content of Both the Objects are SAME
b) The Memory Address of Both the Objects are SAME
c) The Modifications are Depedent ( Whatever the changes we do on one
object,
Which are reflected to another object and both of them are
pointing same memory space)
Syntax: object2=object1
Examples:
---------------------
>>> l1=[10,"Rossum",23.45]
>>> print(l1,id(l1))-----------------[10, 'Rossum', 23.45] 1996956038208
>>> l2=l1 # Deep Copy
>>> print(l2,id(l2))----------------[10, 'Rossum', 23.45] 1996956038208
>>> l1.append("Python")
>>> print(l1,id(l1))---------------[10, 'Rossum', 23.45, 'Python'] 1996956038208
>>> print(l2,id(l2))---------------[10, 'Rossum', 23.45, 'Python'] 1996956038208
>>> l2.insert(1,"Nether")
>>> print(l1,id(l1))--------------[10, 'Nether', 'Rossum', 23.45, 'Python']
1996956038208
>>> print(l2,id(l2))--------------[10, 'Nether', 'Rossum', 23.45, 'Python']
1996956038208
========================x==================================