Nested List Indices: Interpreting Python's Reference-Based Behavior
In Python, lists are treated as mutable, reference-based data structures. This characteristic poses a potential pitfall while working with nested lists, as demonstrated by the following code snippet:
<code class="python">some_list = 4 * [(4 * [0])]</code>
Creating a nested list like this creates four references to the same underlying list. As a result, any modification made to one of the references affects all the others due to their shared nature. This behavior is evident in the provided code, where the expected output:
<code class="python">[0, 0, 0, 0] [0, 1, 1, 1] [0, 1, 1, 1] [0, 1, 1, 1]</code>
Conflicts with the actual output:
<code class="python">[0, 1, 1, 1] [0, 1, 1, 1] [0, 1, 1, 1] [0, 1, 1, 1]</code>
To avoid this gotcha, it's recommended to create a new list instance for each sublist using a comprehension approach:
<code class="python">some_list = [(4 * [0]) for _ in range(4)]</code>
This approach ensures that each sublist is independent, resolving the issue and producing the intended output.
The above is the detailed content of Why Does Modifying a Nested List Element in Python Affect All Its Copies?. For more information, please follow other related articles on the PHP Chinese website!