python notes-deep copy and shallow copy

Deep Copy and Shallow Copy are two ways to copy objects in Python. They have different characteristics and applicable scenarios.

  1. Shallow Copy:

    • Use copy()methods or slicing operations to create shallow copies.
    • Shallow copy creates a new object, but the elements of the object (such as lists, dictionaries, etc.) are still references to the elements in the original object, that is, the elements in the new object share the same memory address as the elements in the original object.
    • Modifying elements in the new object affects corresponding elements in the original object, and vice versa.
    • Suitable for simple data structures or scenarios where part of the data needs to be shared.
  2. Deep Copy:

    • Use deepcopy()a function to create a deep copy, which is located copyin the module.
    • Deep copy creates a new object and recursively copies all elements of the object, including nested lists, dictionaries, etc. Each element is independent and does not share a memory address with the original object.
    • Modifying elements in the new object does not affect elements in the original object, and vice versa.
    • Suitable for complex data structures or scenarios that require completely independent replication.

Sample code:

import copy

# 原始列表
original_list = [1, [2, 3], [4, 5, 6]]

# 浅拷贝
shallow_copy_list = original_list.copy()  # 或者 shallow_copy_list = original_list[:]
shallow_copy_list[0] = 100
shallow_copy_list[1][0] = 200

# 深拷贝
deep_copy_list = copy.deepcopy(original_list)
deep_copy_list[0] = 1000
deep_copy_list[1][0] = 2000

print("原始列表:", original_list)      # 原始列表: [1, [2000, 3], [4, 5, 6]]
print("浅拷贝列表:", shallow_copy_list)  # 浅拷贝列表: [100, [200, 3], [4, 5, 6]]
print("深拷贝列表:", deep_copy_list)    # 深拷贝列表: [1000, [2000, 3], [4, 5, 6]]

In a shallow copy, sublists in the new list are modified, and the original list is also affected. In a deep copy, modifications to the new list will not affect the original list. Depending on specific needs, choosing a suitable copy method can better handle object copying and modification operations.

Features deep copy Shallow copy
Copy content Create a completely independent copy of the target object Create a shallow copy of the target object, sharing part of the memory address
data correlation Does not share memory with the original object, completely independent Shares part of the memory with the original object, modifying one will affect the others
object hierarchy For nested data structures, recursively copies all child objects Only first-level objects are copied, and for nested data structures, only references are copied.
applicability Handle complex data structures and avoid problems caused by data correlation Handle simple data structures or situations where shared memory is required
Application scenarios Prevent modification of original data and save historical status or snapshot of data Generate shallow copies, for copying simple data structures
Multi-threaded or multi-process environment Work with shared data in a multi-threaded or multi-process environment Process independent data in a multi-threaded or multi-process environment
recursive data structure Handle recursive data structures to avoid infinite loops or duplicate elements Data structure suitable for shallow copies to avoid copying large amounts of data
memory consumption May consume more memory as all child objects are copied Memory space may be saved due to sharing part of the memory.

In general, deep copies are suitable for processing complex data structures, preventing modification of the original data, saving historical states or snapshots of data, and processing shared data in multi-threaded or multi-process environments. Shallow copy is suitable for processing simple data structures or situations that require shared memory. It can save memory space but needs to pay attention to problems caused by data correlation. When choosing a copy method, you need to decide whether to use deep copy or shallow copy according to the specific application scenario.

Shallow copies and pointers

Shallow copies and pointers are somewhat similar in that they both involve the issue of shared data. The following is a brief comparison of the similarities and differences between shallow copies and pointers:

Similarities:

  1. Shared memory: Shallow copies and pointers both involve shared memory. When a shallow copy copies an object, it only copies the reference to the object rather than the data itself, so the copied object shares part of the memory with the original object. Pointers also access data through references, so the data pointed to by the pointers and the original data are shared.

  2. Shallow copy: Both shallow copy and pointer copy only the shallow part of the object. Shallow copy only copies the first-level object, and only copies the reference to the nested data structure; the pointer only points to the memory address of the data, but does not copy the data itself.

the difference:

  1. Data copy: When copying an object, a shallow copy creates a new instance of the object and copies the reference, without copying the actual data. The pointer only points to the memory address of the data and does not involve copying the data itself.

  2. Object properties: Shallow copy is performed through specific methods or operations of the object. It is a copy behavior for the object. Pointer is a data type used to store the memory address of data. It does not involve copying of objects.

  3. Impact of modifications: With shallow copies, modifications to the copied object may affect the original object because they share part of the memory. For pointers, modifying the data pointed to by the pointer also affects the original data.

To sum up, shallow copies and pointers both involve shared memory issues, but their essence and application scenarios are different. Shallow copy is a specific object copy behavior that is used to copy the reference of an object without involving the copy of the data itself. It is suitable for scenarios such as preventing modification of the original data and saving the historical state or snapshot of the data. Pointer is a data type used to store the memory address of data and is suitable for situations where data needs to be accessed and modified.

Guess you like

Origin blog.csdn.net/qq_40140808/article/details/131902275