Pit of Python two-dimensional array: vis = [[0]*m] * n

Let's see first, vis = [[0]*m] * nwhat vis2 = [[0]*m for _ in range(n)]'s the difference?

Both lines of code are used to create a two-dimensional list (or matrix), but a key difference between them is how the list is copied.

  • vis = [[0]*m] * n:
    This way creates a list containing n identical sublists. That is, all sublists are actually references to the same list. If you modify an element in one sublist, the corresponding elements in all other sublists will also be modified, since they all point to the same memory location.

  • vis2 = [[0]*m for _ in range(n)]:
    This way creates a list with n independent sublists. With list comprehensions, each sublist is created by [0]*m, so they are distinct in memory and not related to each other.

Here is an example to illustrate the difference between the two approaches:

n = 3
m = 4

vis = [[0]*m] * n
vis2 = [[0]*m for _ in range(n)]

vis[0][0] = 1
vis2[0][0] = 1

print(vis)
print(vis2)

As you can see from the output
insert image description here
, in the first way, modifying the elements of a sublist will affect all other sublists, while in the second way, each sublist is independent, and modifying a sublist will not affect other sublist. Usually, the second way is recommended to create independent two-dimensional lists.

Guess you like

Origin blog.csdn.net/Supreme7/article/details/132114101