Home > Backend Development > Python Tutorial > Shallow vs. Deep Copy in Python Dictionaries: When Does `copy()` Fail?

Shallow vs. Deep Copy in Python Dictionaries: When Does `copy()` Fail?

Mary-Kate Olsen
Release: 2024-11-22 20:20:13
Original
254 people have browsed it

Shallow vs. Deep Copy in Python Dictionaries: When Does `copy()` Fail?

Shallow Copy vs. Deep Copy in Python: Understanding the Effects on Dictionaries

The shallow copy of a dictionary in Python, created using dict.copy(), may not update the original dictionary as expected. This behavior stems from the concept of shallow vs. deep copying.

What is Shallow Copying?

In a shallow copy, the content of the dictionary is referenced, rather than copied by value. This means that both the original and copied dictionaries point to the same underlying data structures.

Demonstration:

>> original = dict(a=1, b=2)
>> new = original.copy()
>> new.update({'c': 3})
>> original
{'a': 1, 'b': 2}
Copy after login

Contrary to the expectation, the original dictionary remains unchanged after the shallow copy is updated. This is because the references to the data are shared, not copied.

How Lists Differ:

Unlike dictionaries, shallow copying lists does result in a shared reference to the data. This is because lists contain values by reference.

>> original = [1, 2, 3]
>> new = original
>> new.append(4)
>> new, original
([1, 2, 3, 4], [1, 2, 3, 4])
Copy after login

In this case, both the original and the new list reference the same data, so changes made to one affect the other.

Deep Copying with copy.deepcopy()

To create a truly distinct copy of a dictionary, including its content, copy.deepcopy() must be used. This function copies the structure and values by value, ensuring complete isolation.

import copy
>> original = dict(a=1, b=2)
>> new = copy.deepcopy(original)
>> new.update({'c': 3})
>> original
{'a': 1, 'b': 2}
>> new
{'a': 1, 'c': 3, 'b': 2}
Copy after login

Types of Copy Operations:

  1. Reference Assignment (a = b): Both variables point to the same object.
  2. Shallow Copy (b = a.copy()): Separate objects, but underlying data is shared.
  3. Deep Copy (b = copy.deepcopy(a)): Completely isolated, with distinct structures and values.

The above is the detailed content of Shallow vs. Deep Copy in Python Dictionaries: When Does `copy()` Fail?. 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