1

I am trying to set all the elements in the principal diagonal of the matrix to be equal to one. Here is my code for the same, using a matrix named "a":

for i in range(len(a)):
    a[i][i] = 1

However, this is setting all elements in a to be 1. I found out that this is because the call a[i][i] is accessing the entire i'th row and not the i'th diagonal element. How do I modify the code to have the intended effect?

  • 1
    You may have defined your array as a list of references to the same list. See https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – xnx Jul 24 '18 at 09:40
  • 1
    @Marcus.Aurelianus what does the diagonal part have to do with the fact that OP has probably created the list in the same fashion than in the linked question and is therefore observing the same behaviour: `a[0][0]` will set all first elements in every row, `a[1][1]` will set all second elements in every row and so on up until you have modified every element in the array. When defining the matrix like `a = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]`, then OP's code works just fine – FlyingTeller Jul 24 '18 at 09:46
  • xnx you are correct. I was using [0]*len(a) so that is what happened. Using list comprehension solved the problem. – BuluBestTapu Jul 24 '18 at 09:47
  • @zwer OP has already confirmed that there was an issue in the list creation – FlyingTeller Jul 24 '18 at 09:49

0 Answers0