python nested list

I encountered a problem today when creating a nested list, and decided to see who was behind it

>>> board1 = [[0]*3 for _ in range(3)]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> board2 = [[0]*3]*3
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Yes, it seems that both methods can create nested lists, but there is a problem when assigning values

>>> board1[1][1] = 1
[[0, 0, 0], [0, 1, 0], [0, 0, 0]]
>>> board2[1][1] = 1
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]

Check the information and find that this is the reason why the 3 references in the board2 list refer to the same object. As a rookie, still puzzled, I saw the following example again

>>> board3 = []
>>> for i in range(3):
... 	row=[0] * 3 
... 	board3.append(row)
...
>>> board3
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> board3[1][1] = 1
>>> board3
[[0, 0, 0], [0, 1, 0], [0, 0, 0]]

board3 and board1 are the same, each iteration creates a new list, meaning that each line of the list points to a different address.

Look at the example below

>>> board4 = []
>>> row=[0] * 3
>>> for i in range(3):
...		board4.append(row)
>>> board4
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> board4[1][1] = 1
>>> board4
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]

board4 and board2 are the same. Each iteration adds the same object to the list, meaning that each row of the list points to the same block address.

Why is this happening?

This is the principle and trap behind references and mutable objects.

The default is to do python shallow copy, if list1a list list(list1) or list1[:]creates list1a copy, they do a shallow copy (copy only the outermost layer of the container, a copy of the elements still refer to the source element in the container). Shallow copy sharing the same list object

In order to clearly understand how they operate, we will visualize the process of creating nested lists below

board1 = [[0]*3 for _ in range(3)]
board1[1][1] = 1
board2 = [[0]*3]*3
board2[1][1] = 1

first row:

First create an iterable object, create in the loop body and [0]*3assign the value to the corresponding position of the new list

You can see, each sub-list occupies a separate space within the nested list, so the assignment board1[1][1] = 1will only change one

The third row:

The three sublists in the nested list point to the same object, so the assignment operation will cause the situation we saw initially.

You can try to enter your own code here to see the visual execution process. Welcome message

Guess you like

Origin www.cnblogs.com/gongyanzh/p/12743501.html