Pythonquestion 16
Pythonquestion 16
In Python, the assignment statement (= operator) does not copy objects. Instead, it creates a
binding between the existing object and the target variable name. To create copies of an
object in Python, we need to use the copy module. Moreover, there are two ways of creating
copies for the given object using the copy module -
• Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of
the values in the original object. If either of the values are references to other objects, just the
reference addresses for the same are copied.
• Deep Copy copies all values recursively from source to target object, i.e. it even duplicates
the objects referenced by the source object.
from copy import copy, deepcopy
## shallow copy
list_2 = copy(list_1)
list_2[3] = 7
list_2[2].append(6)
## deep copy
list_3 = deepcopy(list_1)
list_3[3] = 8
list_3[2].append(7)