Home >Backend Development >Python Tutorial >Shallow vs. Deep Copy in Python Lists: When Should I Use `copy.deepcopy()`?

Shallow vs. Deep Copy in Python Lists: When Should I Use `copy.deepcopy()`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-09 20:51:11805browse

Shallow vs. Deep Copy in Python Lists: When Should I Use `copy.deepcopy()`?

Deep Copying Lists: Beyond Shallow Approaches

When attempting to copy a list using list(...), one might assume it creates a deep copy based on the observation that id(E0) differs from id(E0_copy). However, this assumption is flawed.

Shallow Copying Trap

list(...) does not perform a deep copy, which involves recursively copying inner objects. Instead, it only copies the outermost list, maintaining references to the original inner lists. Thus, modifications to the inner lists affect both the original and the copied list.

Deep Copying with copy.deepcopy

To create a true deep copy, use copy.deepcopy(...). This method recursively copies all levels of objects, ensuring that changes to the copy do not impact the original.

Example

Consider the following code snippet:

>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = list(a)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> a[0][1] = 10
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b   # b changes too -> Not a deepcopy.
[[1, 10, 3], [4, 5, 6]]

In this example, list(...) creates a shallow copy of a. When a[0][1] is modified, b also changes, indicating that they reference the same inner lists.

Contrast this with the following:

>>> import copy
>>> b = copy.deepcopy(a)
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b
[[1, 10, 3], [4, 5, 6]]
>>> a[0][1] = 9
>>> a
[[1, 9, 3], [4, 5, 6]]
>>> b    # b doesn't change -> Deep Copy
[[1, 10, 3], [4, 5, 6]]

Using copy.deepcopy, we create a true deep copy of a. Changes to a do not affect b, confirming that they are distinct objects with their own copies of inner lists.

Conclusion

When deep copying lists is essential, remember to use copy.deepcopy(...) to ensure that changes to the copy do not affect the original. This understanding is crucial for maintaining data integrity and avoiding unexpected consequences in your code.

The above is the detailed content of Shallow vs. Deep Copy in Python Lists: When Should I Use `copy.deepcopy()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn