The python two-dimensional list List modifies one of the values, and the values of all items change.

We create a two-dimensional list as follows:

list1 = [[0,0,0],
        [0,0,0],
        [0,0,0]]

Modify one of the values, such as

list1[1][1] = 2

The result should normally be

list1 = [[0,0,0],
        [0,2,0],
        [0,0,0]]

The above is no problem.

                                                                                                                                                      

But sometimes modifying one of the values ​​will cause all items to change, and the above result becomes

list1 = [[0,2,0],
        [0,2,0],
        [0,2,0]]

The reason is, there is something wrong with the way the 2D array is created. Possible creation methods are

list1 = [[0] * 3] * 3

can be modified to

list1 = [[0] * 3 for _ in range(3)]

Guess you like

Origin blog.csdn.net/nature1949/article/details/119937302