"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why does assigning a list to a new variable in Python not create a separate copy?

Why does assigning a list to a new variable in Python not create a separate copy?

Published on 2024-11-10
Browse:299

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:

vec = v
vec[5] = 5

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:

vec = list(v)

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3