Home >Backend Development >Python Tutorial >Why does assigning a list to a new variable in Python not create a separate copy?
Unexpected List Mutation
When creating a list like v = [0,0,0,0,0,0,0,0,0], you might assume that assigning a new list to a variable creates a separate reference. However, code like the following can demonstrate unexpected behavior:
<code class="python">vec = v vec[5] = 5</code>
Both vec and v now contain the value 5 at the index 5. Why does this happen?
Reference Assignment
In Python, lists are mutable objects. Assigning vec = v does not create a new copy of the list. Instead, it assigns a reference to v. Both vec and v point to the same underlying list object in memory.
Any modifications made to either vec or v will affect the original list because they are the same list. This is why when vec[5] is changed, v also changes.
Solution
To create a separate copy of the list, use the list() function:
<code class="python">vec = list(v)</code>
This creates a new list object that contains a copy of the elements from v. Any changes made to vec will not affect v, and vice versa.
The above is the detailed content of Why does assigning a list to a new variable in Python not create a separate copy?. For more information, please follow other related articles on the PHP Chinese website!