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

Creating a copy of an object in Python is a common task, and it can be done using shallow copy or deepcopy methods. Shallow copy creates a new object but doesn’t create new copies of nested objects, whereas deepcopy creates a new object and recursively creates copies of nested objects. To create a shallow copy of an object, you can use the copy module's copy() function. Here’s an example: import copy original_list = [1, 2, [3, 4]] copied_list = copy.copy(original_list) original_list[2][0] = 5 print(original_list) # Output: [1, 2, [5, 4]] print(copied_list) # Output: [1, 2, [5, 4]] As you can see, the nested list in the copied_list is still referring to the original list. To create a deepcopy of an object, you can use the deepcopy() function from the copy module. Here’s an example: import copy original_list = [1, 2, [3, 4]] deepcopied_list = copy.deepcopy(original_list) original_list[2][0] = 5 print(original_list) # Output: [1, 2, [5, 4]] print(deepcopied_list) # Output: [1, 2, [3, 4]] In this example, the nested list in the deepcopied_list is not affected by changes to the original list. Understanding the difference between shallow copy and deepcopy is important when working with complex data structures in Python. By using these methods, you can effectively create copies of objects without inadvertently affecting the original object. Whether you need to create a shallow copy or a deepcopy depends on the specific requirements of your program. With these techniques, you can easily manage and manipulate objects in Python without the risk of unintended side effects.

Recommend