
Python copy and deepcopy - What is the difference of assignment, copy, and deepcopy?
The difference of dictionary assignment, copy, and deepcopy is found when updating the original dictionary.
import copy
d = {'x': 1, 'y': '2', 'z': [3, 4]}
d_assign = d
d_copy = d.copy()
d_deepcopy = copy.deepcopy(d)
d.pop('x')
d['z'][0] = 7
print(d) # {'y': '2', 'z': [7, 4]}
print(d_assign) # {'y': '2', 'z': [7, 4]}
print(d_copy) # {'x': 1, 'y': '2', 'z': [7, 4]}
print(d_deepcopy) # {'x': 1, 'y': '2', 'z': [3, 4]}
This article brings up dictionary but all are the same as list.
Assignment
d = {'x': 1, 'y': '2', 'z': [3, 4]}
d_assign = d
d.pop('x')
d['z'][0] = 7
print(d) # {'y': '2', 'z': [7, 4]}
print(d_assign) # {'y': '2', 'z': [7, 4]}
Because both d_assign
and d
are the same, updating d
changes d_assign
. Because of this behavior, the copy()
is needed when using the original and new dictionaries.
Copy
import copy
d = {'x': 1, 'y': '2', 'z': [3, 4]}
d_assign = d
d_copy = copy.copy(d)
d.pop('x')
d['z'][0] = 7
print(d) # {'y': '2', 'z': [7, 4]}
print(d_assign) # {'y': '2', 'z': [7, 4]}
print(d_copy) # {'x': 1, 'y': '2', 'z': [7, 4]}
The keys and some values of d_copy
don't change by updating d
and d_copy
has actually x
. But the z
value of d_copy
changes. The copy.copy()
is not "perfect" copying.
Deepcopy
import copy
d = {'x': 1, 'y': '2', 'z': [3, 4]}
d_assign = d
d_copy = copy.copy(d)
d_deepcopy = copy.deepcopy(d)
d.pop('x')
d['z'][0] = 7
print(d) # {'y': '2', 'z': [7, 4]}
print(d_assign) # {'y': '2', 'z': [7, 4]}
print(d_copy) # {'x': 1, 'y': '2', 'z': [7, 4]}
print(d_deepcopy) # {'x': 1, 'y': '2', 'z': [3, 4]}
The z
value of d_deepcopy
doesn't change by changing d
. So the copy is called "deep".
Assignment and copy of int
The above examples show the assignment, copy, and deepcopy of dictionary. Now, let's check those of an immutable value.
a = 2
b = a + 1
print(b) # 3
a = 5
print(b) # 3
The b
doesn't change by changing a
. That's because both are integers and immutable. So we don't need copying to maintain immutable values.
Comments
Powered by Markdown