How do Shallow and Deep Copying Differ in Python?

Susan Sarandon
Release: 2024-11-07 05:22:03
Original
604 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!