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
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
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)]
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!