Home > Backend Development > Python Tutorial > Does Python Create Copies or References When Assigning Objects?

Does Python Create Copies or References When Assigning Objects?

DDD
Release: 2024-12-16 18:50:15
Original
166 people have browsed it

Does Python Create Copies or References When Assigning Objects?

Does Python Copy Objects on Assignment?

In Python, assignment of variables does not create copies of objects but rather references to them. This behavior can lead to unexpected results.

Example:

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

Unexpectedly, this code produces the following output:

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

Explanation:

When you assign dict_a = dict_b = dict_c = {}, you are not creating three separate dictionaries. Instead, you are creating one dictionary and assigning three names (references) to it. As a result, any modifications made to one of the references affect all of them.

Solution:

To create independent copies of objects, you can use either the dict.copy() method or copy.deepcopy() function.

Using dict.copy():

dict_a = dict_b.copy()
dict_c = dict_b.copy()
Copy after login

Using copy.deepcopy():

import copy
dict_a = copy.deepcopy(dict_b)
dict_c = copy.deepcopy(dict_b)
Copy after login

The above is the detailed content of Does Python Create Copies or References When Assigning 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