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