Sometimes, we want to create a copy of an object in Python.
In this article, we’ll look at how to create a copy of an object in Python.
How to create a copy of an object in Python?
To create a copy of an object in Python, we can use the copy.copy
method to create a shallow copy of an object.
We can use copy.deepcopy
to create a deep copy of an object.
For instance, we write
import copy
class C():
def __init__(self):
self.x = [1]
self.y = [2]
c = C()
d = copy.copy(c)
to create a shallow copy of object c
and assign it to d
.
Likewise, we write
d = copy.deepcopy(c)
to create a deep copy of object c
and assign it to d
.
Conclusion
To create a copy of an object in Python, we can use the copy.copy
method to create a shallow copy of an object.
We can use copy.deepcopy
to create a deep copy of an object.