Home >Backend Development >Python Tutorial >Why Does Changing a Copy Variable Affect the Original Variable in Python?
Python: Why Changing a Copy Variable Affects the Original Variable
In Python, you may encounter a peculiar behavior where modifications made to a copy variable appear to alter the original variable as well. This occurs because Python variables store references rather than actual values.
To understand this, consider the situation described:
org_list = ['y', 'c', 'gdp', 'cap'] copy_list = org_list # Pass reference to org_list copy_list.append('hum') print(copy_list) # ['y', 'c', 'gdp', 'cap', 'hum'] print(org_list) # ['y', 'c', 'gdp', 'cap', 'hum']
When you assign copy_list to org_list, you are not creating a new list but rather establishing a reference to the same list object in memory. Hence, any changes to either copy_list or org_list directly affect both variables.
To create a truly independent copy, you need to pass a copy of the actual data, rather than a reference. This can be done by using the slice assignment operator:
copy_list = org_list[:] # Create a deep copy by slicing
By slicing the original list, you create a new list object with its own copy of the data. Any modifications made to copy_list will not affect org_list, and vice versa.
The above is the detailed content of Why Does Changing a Copy Variable Affect the Original Variable in Python?. For more information, please follow other related articles on the PHP Chinese website!