Modelo

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

Creating a Copy of an Object in Python

Oct 19, 2024

In Python, when working with objects, it’s common to need to create a copy of an object. This is especially important when you want to modify an object without affecting the original. There are two main ways to create a copy of an object in Python: shallow copy and deep copy. Shallow copy creates a new object but doesn’t create new copies of any objects within the original object. Deep copy, on the other hand, creates a new object and also creates new copies of any objects within the original object. To create a shallow copy of an object, you can use the copy module's copy() function. This function creates a shallow copy of the object. If the object contains references to other objects, the copy will also contain references to the same objects. To create a deep copy of an object, you can use the copy module's deepcopy() function. This function creates a deep copy of the object, including all nested objects within it. This ensures that the new copy is independent of the original object and any changes made to the original object won’t affect the new copy. Here’s an example of how to create a shallow copy and a deep copy of a list: import copy original_list = [1, [2, 3], 4] shallow_copy = copy.copy(original_list) deep_copy = copy.deepcopy(original_list) original_list[1][0] = 'a' print(original_list) # Output: [1, ['a', 3], 4] print(shallow_copy) # Output: [1, ['a', 3], 4] print(deep_copy) # Output: [1, [2, 3], 4] As you can see, when we modify the nested list within the original list, the change is reflected in both the original list and the shallow copy, but not in the deep copy. This demonstrates the difference between shallow copy and deep copy. By understanding how to create copies of objects in Python, you can ensure that you can work with objects in a way that meets your specific needs. Whether you need a shallow copy or a deep copy, Python provides the tools you need to create independent copies of your objects.

Recommend