Python Assignment
Direct assignment
Object reference
| In [1]: a = {1: [1,2,3]}
In [2]: b=a
In [3]: a[0]=[1,1]
In [4]: b
Out[4]: {1: [1, 2, 3], 0: [1, 1]}
|
Copy
Copying the parent object does not copy the child object inside the object
| In [5]: a = {1: [1,2,3]}
In [6]: b = a.copy()
In [7]: a, b
Out[7]: ({1: [1, 2, 3]}, {1: [1, 2, 3]})
In [8]: a[1].append(4)
In [9]: a, b
Out[9]: ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
|
Deep Copy
The parent object and its child objects are completely copied
| In [10]: import copy
In [11]: c = copy.deepcopy(a)
In [12]: a, c
Out[12]: ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
In [13]: a[1].append(5)
In [14]: a, c
Out[14]: ({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})
|