Python stepping on the pit: using the multiplication sign in the list to copy multiple empty lists

The following code:

>>> a = [[]] * 3
>>> b = []
>>> for i in range(3):
...    b.append([])
>>> a == b
True
>>> a
[[], [], []]
>>> b
[[], [], []]

From the above results, [[]] * 3it is true that an empty list is created [[], [], []], but when we assign values, the following unexpected situations will occur:

>>> a[0].append(1)
>>> b[0].append(1)
>>> a == b
False
>>> a
[[1], [1], [1]]
>>> b
[[1], [], []]

The reason for this is that when copying with a multiplication sign *, only the index is copied, that is, the copied n indexes all point to the same physical address, so when any one of them is operated, other content will be modified at the same time. Similarly, multiple empty dictionaries in the list are also the same problem.

Elegant solution to this problem (with list comprehensions):

>>> a  = [[] for i in range(3)]
>>> a
[[], [], []]
>>> a[0].append(1)
>>> a
[[1], [], []]

Guess you like

Origin blog.csdn.net/MrTeacher/article/details/102518289