How can I create a copy of an object in Python?
How can I create a copy of an object in Python?
In Python, creating a copy of an object can be done using the copy module, which provides two main functions: copy() for creating shallow copies and deepcopy() for creating deep copies.
A shallow copy creates a new compound object and then inserts references into it to the objects found in the original. This means that the new compound object will have its own identity, but the elements within it may still reference the same objects as those in the original compound object. To create a shallow copy, you can use the copy.copy() function.
Here's an example of creating a shallow copy of a list:
import copy
original_list = [1, 2, [3, 4]]
shallow_copied_list = copy.copy(original_list)
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original. This means that not only the compound object is copied, but also all objects it contains, creating a fully independent object. To create a deep copy, you can use the copy.deepcopy() function.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.