Home > Backend Development > Python Tutorial > Why Does Python Assignment Show Unexpected Behavior with Mutable Objects?

Why Does Python Assignment Show Unexpected Behavior with Mutable Objects?

DDD
Release: 2024-12-07 20:25:16
Original
502 people have browsed it

Why Does Python Assignment Show Unexpected Behavior with Mutable Objects?

Copy-Through Behavior in Python Assignment

Introduction

Python, a popular programming language, presents a peculiar behavior when assigning objects to variables through the assignment operator (=). This behavior, commonly referred to as copy-through, often leads to unexpected results. To unravel this concept, let's examine a common example.

The Problem: Copy-Through vs. Copy

Consider the following code:

dict_a = dict_b = dict_c = {}
dict_c['hello'] = 'goodbye'

print(dict_a)
print(dict_b)
print(dict_c)
Copy after login

One would expect this code to create three separate dictionaries, initialize them to empty, and then modify only dict_c. The expected output should be:

{}
{}
{'hello': 'goodbye'}
Copy after login

However, Python's copy-through behavior yields a different result:

{'hello': 'goodbye'}
{'hello': 'goodbye'}
{'hello': 'goodbye'}
Copy after login

Explanation: Reference Assignment

The key to understanding this behavior lies in the nature of variables in Python. In Python, variables (or names) are merely pointers to the actual objects stored in memory. When you assign one variable to another, the assignment operator (=) copies the memory address (or pointer) from one variable to another. In our example:

dict_a = dict_b = dict_c
Copy after login

This means that dict_a, dict_b, and dict_c all point to the same dictionary object in memory. When dict_c is modified, therefore, all three variables see the same modification, resulting in the copy-through effect.

Resolving the Issue: Using Copy Methods

To prevent the copy-through behavior, one must explicitly create a copy of the underlying object. Python provides two methods for this purpose:

  • dict.copy(): Creates a shallow copy that copies the top-level elements of the dictionary.
  • copy.deepcopy(): Creates a deep copy that recursively copies all nested objects within the dictionary.

Example:

dict_a = dict_b.copy()
dict_c = copy.deepcopy(dict_a)

dict_c['hello'] = 'goodbye'

print(dict_a)  # {'hello': 'goodbye'} (shallow copy, affected)
print(dict_b)  # {} (unaffected)
print(dict_c)  # {'hello': 'goodbye'} (deep copy, unaffected)
Copy after login

By using these copy methods, we can create independent copies of objects and avoid the copy-through behavior.

The above is the detailed content of Why Does Python Assignment Show Unexpected Behavior with Mutable Objects?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template