Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

How to Create a Copy of an Object in Python

Oct 09, 2024

In Python, when you want to create a copy of an object, you can use the copy module. The copy module provides a simple way to create shallow copies of objects. You can use the copy() method to create a shallow copy of an object. This means that the new object will be a separate copy, but the internal objects will still be references to the original object's internal objects.

If you want to create a deep copy of an object, you can use the deepcopy function from the copy module. The deepcopy function creates a new object and recursively copies all the objects it contains, and all the objects they contain, and so on. This ensures that the new object is completely independent of the original object.

Here's an example of how to create a shallow copy of a list using the copy module:

import copy

original_list = [1, 2, 3]

shallow_copy = copy.copy(original_list)

print(shallow_copy) # Output: [1, 2, 3]

If you modify the shallow copy, it will not affect the original list, but if you modify the internal objects of the original list, it will affect the shallow copy.

Here's an example of how to create a deep copy of a list using the deepcopy function:

import copy

original_list = [[1, 2], [3, 4]]

deep_copy = copy.deepcopy(original_list)

print(deep_copy) # Output: [[1, 2], [3, 4]]

If you modify the deep copy, it will not affect the original list or its internal objects.

These methods can be especially useful when working with complex data structures or when you want to avoid unintended side effects when modifying objects. By using the copy module and the deepcopy function, you can ensure that your copied objects are truly independent of the original objects.

Recommend