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

Does Python Create Copies or References When Assigning Objects?

DDD
DDDOriginal
2024-12-16 18:50:15237browse

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)

Unexpectedly, this code produces the following output:

{'hello': 'goodbye'}
{'hello': 'goodbye'}
{'hello': 'goodbye'}

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()

Using copy.deepcopy():

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

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!

Statement:
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