If you create a matrix of n by n from zeros by multiplying the lists
n = 3 a = [[0]*n]*n
And then equate the first element of the main diagonal 1, then the entire first column will consist of 1. Why?
a[0][0] = 1 print(a) #[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
I understand this because, when multiplying, we simply created several links to one list. But if you multiply the list only once, then there are no such problems. Why?
n = 3 a = [[0]*n for i in range(n)] a[0][0] = 1 print(a) #[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
a
is not a list ofn
copies of[0]*n
, each a element points to the same list. In the case of[0]*n
this is normal -0
immutable element, it can only be replaced and not changed , but the list of lists is another matter. - extrn