Python—list list, two-dimensional unequal length

Need to create a two-dimensional list, unequal length. What I thought of was to create a one-dimensional list first, and then use the append function to add the elements, but found that this would add the same elements to all elements in the list.

code show as below:

list_01 = [[]] * 3
list_01[0].append([1,2])
print("list_01为:",list_01)

Output result:

list_01为: [[[1, 2]], [[1, 2]], [[1, 2]]]

Then I searched and found this article https://crypto.blog.csdn.net/article/details/106454135.
It turned out to be the reason for deep copy and shallow copy. The elements in the first method list point to the same address. One of the definition methods that can avoid this situation is as follows:

code show as below:

list=[[] for i in range(3)]
list[0].append([1,2])
print("list为:",list)

Output result:

list为: [[[1, 2]], [], []]

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_47470899/article/details/114107045