Home >Backend Development >Python Tutorial >Why Does Modifying a List Variable in Python Also Affect Another Variable Assigned to It?
Unexpected List Mutations: Understanding the Effects of References
In Python, list variables represent references to arrays stored in memory. When assigning one list variable to another (e.g., vec = v), what's actually happening is that the address of the array is passed instead of copying the array itself.
This means that any modifications made to one list will also affect the other list that points to the same memory address. For example, consider the following code:
<code class="python">v = [0,0,0,0,0,0,0,0,0] vec = v vec[5] = 5</code>
After executing the above code, both v and vec will contain the following values:
[0, 0, 0, 0, 0, 5, 0, 0, 0]
This happens because vec and v both reference the same array in memory. When the value at index 5 in vec is modified to 5, the change is not only reflected in vec, but also in v, since both variables point to the same underlying array.
To create true copies of a list, use the copy() method or the list() constructor with the original list as an argument, as shown below:
<code class="python">vec = v.copy() vec = list(v)</code>
The above is the detailed content of Why Does Modifying a List Variable in Python Also Affect Another Variable Assigned to It?. For more information, please follow other related articles on the PHP Chinese website!