If you use Python Initializes a length of n One dimension of list, It's simple , just :
ls = [0] * n
The initialization element is n individual 0. But for two-dimensional , If you simply extend this method, it is easy to make mistakes :
ls = [[0] * n] * m
There will be problems . Put each dimension list As an element , The above code will only [[0] * n] Reference copy for m times , It won't open up m*n A unit of memory space to .
This is the time , Satisfy ls[0] With the address of ls[1],…, ls[m-1] Your address is exactly the same :
id(ls[0]) == id(ls[1])
# True
At this time , change ls[0] The value of will change to ls[1] The numerical .
I believe this initialization effect , Not the original intention of the coders ~
If necessary m*n What to do with a unit of memory space ?
as follows :
ls = [[0] * n for _ in range(m)]