About the definition of python's two-dimensional array

Recently, when using python's two-dimensional array, I found a problem:
When using arr = [[0] * n] * nthis form, it is found that when one data in the array is modified, the data in one column will be changed at the same time. The search found that it is a problem of the reference mechanism. The principle analysis: two Dimensional array reference explanation .


So how do we define a two-dimensional array that can modify the data?
You can use this form:
arr = [[0] * n for i in range(n)]

Note: [0] * n is a one-dimensional array, for i in range(n) is to loop the one-dimensional array n times to realize a two-dimensional array

Guess you like

Origin blog.csdn.net/lxxlxx888/article/details/105258965