0
0
PythonProgramBeginner · 2 min read

Python Program to Find Sum of Diagonal Elements

You can find the sum of diagonal elements of a square matrix in Python by using sum(matrix[i][i] for i in range(len(matrix))) which adds elements where row and column indexes are equal.
📋

Examples

Input[[1,2],[3,4]]
Output5
Input[[5,1,0],[2,8,3],[1,0,6]]
Output19
Input[[7]]
Output7
🧠

How to Think About It

To find the sum of diagonal elements, look at the matrix positions where the row number and column number are the same. Add all these elements together to get the total sum.
📐

Algorithm

1
Get the square matrix as input.
2
Initialize a variable to store the sum as zero.
3
Loop through the matrix indexes from 0 to size-1.
4
Add the element at position [i][i] to the sum.
5
Return or print the sum.
💻

Code

python
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))
Output
19
🔍

Dry Run

Let's trace the matrix [[5,1,0],[2,8,3],[1,0,6]] through the code

1

Initialize total

total = 0

2

i = 0

Add matrix[0][0] = 5 to total, total = 5

3

i = 1

Add matrix[1][1] = 8 to total, total = 13

4

i = 2

Add matrix[2][2] = 6 to total, total = 19

5

Return total

Return 19

imatrix[i][i]total
055
1813
2619
💡

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

Using list comprehension and sum()
python
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))
This method is shorter and more Pythonic but may be less clear for beginners.
Using numpy library
python
import numpy as np
matrix = np.array([[5,1,0],[2,8,3],[1,0,6]])
print(np.trace(matrix))
Using numpy's trace function is very efficient but requires installing an external library.

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.

ApproachTimeSpaceBest For
Loop with forO(n)O(1)Beginners, clarity
List comprehension + sumO(n)O(1)Concise Python code
Numpy traceO(n)O(n) for numpy arrayLarge matrices, performance
💡
Make sure your matrix is square (same number of rows and columns) before summing diagonal elements.
⚠️
Trying to sum diagonal elements in a non-square matrix without checking size can cause errors or wrong results.