Home > Backend Development > Python Tutorial > Does Python Assignment Create Copies or References to Objects?

Does Python Assignment Create Copies or References to Objects?

Susan Sarandon
Release: 2024-12-19 12:25:14
Original
212 people have browsed it

Does Python Assignment Create Copies or References to Objects?

Does Python Assign References or Copies?

Problem:

Python's assignment behavior can be confusing when working with objects like dictionaries. 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

Expected Output:

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

Actual Output:

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

Explanation:

Python variables refer to objects in memory. When you assign dict_a = dict_b, you are not copying the dictionary object itself but rather assigning a reference to the same memory address as dict_b. This means that changes made to one dictionary will affect all three variables since they are pointing to the same underlying object.

Solution:

To create a true copy of an object in Python, you need to use the copy or copy.deepcopy functions. The following code will create independent copies of the original dictionary:

dict_a = dict_b.copy()  # Shallow copy
dict_a = copy.deepcopy(dict_b)  # Deep copy
Copy after login
  • Shallow copy: Creates a new dictionary that references the same nested objects as the original.
  • Deep copy: Creates a new dictionary and recursively copies all nested objects.

By using these functions, you can ensure that changes made to one dictionary do not affect the others.

The above is the detailed content of Does Python Assignment Create Copies or References to 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template