"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Do Lists Linked Together When Using [[]] * n in Python List Initialization?

Why Do Lists Linked Together When Using [[]] * n in Python List Initialization?

Published on 2024-11-05
Browse:275

Why Do Lists Linked Together When Using [[]] * n in Python List Initialization?

List Linking Issue in List Initialization with [[]] * n

When initializing a list of lists using [[]] n, programmers often encounter an unexpected issue where the lists appear to be linked together. This occurs because the [x]n syntax creates multiple references to the same underlying list object, rather than creating distinct list instances.

To illustrate the problem, consider the following code:

x = [[]] * 3
x[1].append(0)
print(x)

The output of this code is:

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

Instead of the expected output:

[[], [0], []]

The issue stems from the fact that each element in the list is a reference to the same list object. When one of the elements is modified, all other elements are affected.

To create a list of truly distinct lists, the correct approach is to use list comprehension:

x = [[] for i in range(3)]

This syntax creates a new list object for each element in the list, ensuring that they are independent.

The following code serves as a demonstration:

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time
Release Statement This article is reprinted at: 1729212379 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3