Home > Backend Development > Python Tutorial > Why Does Modifying One List Affect Another in Python?

Why Does Modifying One List Affect Another in Python?

DDD
Release: 2024-11-02 12:37:02
Original
920 people have browsed it

Why Does Modifying One List Affect Another in Python?

Unexpectedly Linked Lists in Python

When working with lists in Python, unexpected behaviors may arise. Let's understand why changing one list unexpectedly affects another.

Problem:

Consider the following Python code:

<code class="python">v = [0, 0, 0, 0, 0, 0, 0, 0, 0]
vec = v  # Assignment by reference
vec[5] = 5</code>
Copy after login

After this code executes, both v and vec show the modified value at index 5:

>>> print(vec)
[0, 0, 0, 0, 0, 5, 0, 0, 0]
>>> print(v)
[0, 0, 0, 0, 0, 5, 0, 0, 0]
Copy after login

Why does v change even though it wasn't explicitly modified?

Understanding the Issue:

In Python, when you assign a list to a new variable, you are not creating a copy; instead, you are creating a reference. This means that both v and vec point to the same underlying list object in memory.

Solution:

To have two separate lists with identical values, you need to create a copy using the list() constructor:

<code class="python">vec = list(v)  # Creates a copy</code>
Copy after login

Now, when you make changes to vec, v will remain unaffected.

The above is the detailed content of Why Does Modifying One List Affect Another in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template