Home  >  Article  >  Backend Development  >  Why Do Nested Lists in Python Share the Same Underlying Data?

Why Do Nested Lists in Python Share the Same Underlying Data?

DDD
DDDOriginal
2024-10-31 07:46:02272browse

Why Do Nested Lists in Python Share the Same Underlying Data?

Nested List Indices

In Python, nested lists can be created using a list of lists. However, when modifying values within these lists, a common pitfall arises due to Python's reference handling.

Consider the following code:

<code class="python">some_list = 4 * [(4 * [0])]
for i in range(3):
    for j in range(3):
        some_list[i + 1][j + 1] = 1
for i in range(4):
    print(some_list[i])</code>

The intended output is:

[0, 0, 0, 0]
[0, 1, 1, 1]
[0, 1, 1, 1]
[0, 1, 1, 1]

However, the actual output is:

[0, 1, 1, 1]
[0, 1, 1, 1]
[0, 1, 1, 1]
[0, 1, 1, 1]

Understanding the Issue

The issue stems from the line some_list = 4 * [(4 * [0])]. Here, the [(4 * [0])] expression creates a single list with four elements, each being a list with four zeros. However, the subsequent multiplication 4 * creates four references to the same list, rather than four distinct lists.

As a result, when a value is modified within one element of some_list, it also affects the other elements because they all point to the same underlying list. This behavior is known as reference passing in Python.

Solution

To resolve this issue and create independent lists within some_list, a loop can be used to create each sublist individually, as follows:

<code class="python">some_list = [(4 * [0]) for _ in range(4)]</code>

This code creates four distinct lists, each with four zeros. Modifying a value within one sublist will no longer affect the other sublists.

The above is the detailed content of Why Do Nested Lists in Python Share the Same Underlying Data?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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