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

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

Linda Hamilton
Release: 2025-01-01 11:10:09
Original
929 people have browsed it

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

Nested List Mutations: Understanding Unexpected Behavior

In Python, mutable data structures such as lists can behave unexpectedly when it comes to nesting. Consider the example where a list of lists is created:

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

This initializes a nested list structure where each sublist contains four elements set to 1. However, modifying one of these innermost values, as shown below:

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

affects all the first elements of every sublist, resulting in:

[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
Copy after login

Cause of the Unexpected Behavior

The root of the issue lies in how the * operator works when applied to objects. In this case, the line:

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

creates three references to the same sublist [1] 4, rather than creating three independent copies. This is because operates on the result of evaluating the expression [1] * 4, which is a single sublist. As a result, any changes to this single sublist are reflected across all references.

Resolving the Issue

To create independent sublists, it's necessary to force an evaluation of the [1] * 4 expression for each sublist. This can be achieved using a list comprehension, as seen below:

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

In this case, the [1]*4 expression is evaluated every time, resulting in the creation of three distinct sublists, and any changes to one sublist will only affect that sublist and not the others.

The above is the detailed content of Why Does Modifying a Nested List in Python Unexpectedly 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