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!