Python Program to Find Sum of Diagonal Elements
sum(matrix[i][i] for i in range(len(matrix))) which adds elements where row and column indexes are equal.Examples
How to Think About It
Algorithm
Code
def sum_diagonal(matrix): total = 0 for i in range(len(matrix)): total += matrix[i][i] return total # Example usage matrix = [[5,1,0],[2,8,3],[1,0,6]] print(sum_diagonal(matrix))
Dry Run
Let's trace the matrix [[5,1,0],[2,8,3],[1,0,6]] through the code
Initialize total
total = 0
i = 0
Add matrix[0][0] = 5 to total, total = 5
i = 1
Add matrix[1][1] = 8 to total, total = 13
i = 2
Add matrix[2][2] = 6 to total, total = 19
Return total
Return 19
| i | matrix[i][i] | total |
|---|---|---|
| 0 | 5 | 5 |
| 1 | 8 | 13 |
| 2 | 6 | 19 |
Why This Works
Step 1: Identify diagonal elements
Diagonal elements are those where the row and column indexes are the same, like matrix[0][0], matrix[1][1], etc.
Step 2: Sum these elements
Add each diagonal element to a running total using total += matrix[i][i].
Step 3: Return the sum
After looping through all indexes, return the total sum which is the sum of diagonal elements.
Alternative Approaches
def sum_diagonal(matrix): return sum(matrix[i][i] for i in range(len(matrix))) matrix = [[5,1,0],[2,8,3],[1,0,6]] print(sum_diagonal(matrix))
import numpy as np matrix = np.array([[5,1,0],[2,8,3],[1,0,6]]) print(np.trace(matrix))
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through the matrix once along the diagonal, so it takes linear time proportional to the matrix size n.
Space Complexity
Only a few variables are used to store sums and indexes, so space used is constant.
Which Approach is Fastest?
Using list comprehension with sum() is concise and fast; numpy's trace is fastest for large matrices but requires extra library.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop with for | O(n) | O(1) | Beginners, clarity |
| List comprehension + sum | O(n) | O(1) | Concise Python code |
| Numpy trace | O(n) | O(n) for numpy array | Large matrices, performance |