Home >Backend Development >Python Tutorial >Why Does Modifying \'vec\' Also Change \'v\' in Python?

Why Does Modifying \'vec\' Also Change \'v\' in Python?

DDD
DDDOriginal
2024-11-03 04:08:31225browse

Why Does Modifying 'vec' Also Change 'v' in Python?

Lists and References: Understanding Variable Assignment in Python

In Python, variables that refer to lists can exhibit unexpected behavior. Consider the following code:

<code class="python">v = [0] * 9
vec = v  # Assign v's address to vec
vec[5] = 5  # Modify vec at index 5
print(v)  # Also prints [0, 0, 0, 0, 0, 5, 0, 0, 0]</code>

Surprisingly, printing 'v' shows that it has also been modified. This behavior can be confusing at first.

Why Does 'v' Change?

The reason for 'v' changing is that vec and v are both references. When you assign vec = v, you're not creating a new list. Instead, you're simply assigning v's address, which is a memory pointer, to vec.

As a result, both vec and v point to the same list in memory. Any changes made to either variable will affect the underlying list, which is why 'v' also changes when 'vec' is modified.

Creating Separate Lists

To create two separate lists, you need to perform a shallow copy:

<code class="python">vec = list(v)</code>

This creates a new list with the same values as 'v' but stores it in a different memory location. Now, modifying 'vec' will not affect 'v'.

The above is the detailed content of Why Does Modifying \'vec\' Also Change \'v\' in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn