P4.3.1Matrix trace
Use a list comprehension to calculate the trace of the matrix M (that is, the sum of its diagonal elements).
Hint: the sum built-in function takes an iterable object and sums its values.
Show solution
With a list comprehension, the matrix trace can be calculated with a single statement.
>>> M = [[1,2,3],
... [4,5,6],
... [7,8,9]]
...
>>> trace = sum(M[i][i] for i in range(3))
>>> print('The trace of M is', trace)
The trace of M is 15