Home > Backend Development > Python Tutorial > Why Does Modifying a Sublist in a Nested Python List Affect All Sublists?

Why Does Modifying a Sublist in a Nested Python List Affect All Sublists?

Barbara Streisand
Release: 2024-12-29 07:50:12
Original
321 people have browsed it

Why Does Modifying a Sublist in a Nested Python List Affect All Sublists?

Nested List Mutability Confusion in Python

Introduction:

In Python, a common issue arises when dealing with nested lists. Changes made to a sublist unexpectedly affect all other sublists in the outer list. This unexpected behavior stems from the underlying mechanism of list creation and mutability.

The Issue:

Consider the following code:

xs = [[1] * 4] * 3
Copy after login

This code creates a list of lists, where each sublist contains four 1s. However, modifying one of the innermost elements, as shown below, affects all sublists:

xs[0][0] = 5
Copy after login

Instead of changing only the first element of the first sublist, all first elements of all sublists are modified to 5.

Reason:

The key to understanding this behavior lies in the way Python multiplies sequences. When using the * operator on an existing list [x], it doesn't create new lists. Instead, it creates multiple references to the same list object.

As a result, in the code xs = [[1] * 4] * 3, the expression [1] * 4 is evaluated once, and three references to that single list are assigned to the outer list. This means all sublists are the same object.

Solution:

To create independent sublists, you can use a list comprehension:

xs = [[1] * 4 for _ in range(3)]
Copy after login

In this case, the list comprehension reevaluates the [1] * 4 expression for each iteration, resulting in three distinct lists.

Immutability of Integers:

It's important to note that integers in Python are immutable, meaning their value cannot be changed. Therefore, even though the * operator creates multiple references to the same list, the values of the integers within that list remain unaffected.

The above is the detailed content of Why Does Modifying a Sublist in a Nested Python List Affect All Sublists?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template