I am trying to find out the sum of the diagonal elements in a matrix. Here, n is the size of the square matrix and a is the matrix. Can someone explain this to me what is happen
Try this for summing your second diagonal:
sum(a[i][n-i-1] for i in range(n))
The inner loop accesses these entries:
>>> n = 3
>>> [(i, n-i-1) for i in range(n)]
[(0, 2), (1, 1), (2, 0)]
And the summed value of this diagonal for your sample matrix is:
>>> n = 3
>>> sum(a[i][n-i-1] for i in range(n))
19
The mistake in your code is to use the same expression for both dimensions:
a[n-i-1][n-i-1]
which will process the first diagonal again in reverse order [(2, 2), (1, 1), (0, 0)]
giving you the same sum twice.