Home >Backend Development >Python Tutorial >How do Shallow and Deep Copying Differ in Python?

How do Shallow and Deep Copying Differ in Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-07 05:22:03687browse

How do Shallow and Deep Copying Differ in Python?

Copying Objects in Python

Creating an independent copy of an object is a common task in programming. In Python, there are two main ways to copy an object: shallow copying and deep copying.

Shallow Copying

Python's default copying mechanism is shallow copying. This means that a new object is created with a reference to the same fields as the original object. Any changes made to the fields of the new object will also be reflected in the original object.

Deep Copying

Deep copying, on the other hand, creates a new object with separate copies of the fields from the original object. This means that any changes made to the fields of the new object will not affect the original object.

To get a fully deep independent copy of an object in Python, you can use the copy.deepcopy() function. Here's an example:

<code class="python">import copy

# Original object
obj = {
    "name": "Alice",
    "age": 20
}

# Create a shallow copy
shallow_copy = obj

# Create a deep copy
deep_copy = copy.deepcopy(obj)

# Modify the shallow copy
shallow_copy["name"] = "Bob"

# Print the original and deep copy
print(obj)  # Output: {'name': 'Bob', 'age': 20}
print(deep_copy)  # Output: {'name': 'Alice', 'age': 20}</code>

As you can see, the deep_copy retains the original values of the object, while the shallow_copy is affected by the changes made to the original object.

The above is the detailed content of How do Shallow and Deep Copying Differ in Python?. 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