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]] 
  • 2
    a is not a list of n 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

1 answer 1

The main nuances that you need to know to answer your question:

  1. Multiplying the list by an integer creates a longer list in which the SAME OBJECTS that were in the original list are repeated several times.

  2. Using the structure of the form [выражение for i in iterator] at each iteration re-evaluates expressions and the list will consist of DIFFERENT OBJECTS, although in certain cases they may be equal to each other (as in your case).

Well, after that everything is easy. In the first case, a is a list in which ONE AND TOT is repeated three times. And if you change an element in it, then in all three positions we see a change, because these are just three displays of the same list. In the second case, through the list inclusion, you have created a list of THREE DIFFERENT lists, which simply have the same value at the moment, but they are not related to each other, and if you change one of them, it will not affect the others.