Editor

Python Program to Check if a Matrix Is Symmetric

Intermediate · Matrices

A square matrix is symmetric when it equals its own transpose, which means the entry in row i, column j always equals the entry in row j, column i. The matrix looks like a mirror image across its main diagonal. This program checks two matrices and points out where a non-symmetric one breaks the rule.

Program

symmetric_matrix.py
def first_mismatch(matrix):
# Compare each entry above the diagonal with its mirror image below it
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
if matrix[i][j] != matrix[j][i]:
return i, j
return None # no mismatch found
samples = [
[[1, 7, 3],
[7, 4, 5],
[3, 5, 6]],
[[1, 2, 0],
[3, 4, 5],
[0, 5, 6]],
]
for matrix in samples:
print("Matrix:")
for row in matrix:
print(row)
spot = first_mismatch(matrix)
if spot is None:
print("It is symmetric")
else:
i, j = spot
print(f"Not symmetric: matrix[{i}][{j}] is {matrix[i][j]} but matrix[{j}][{i}] is {matrix[j][i]}")
print()
Output
Matrix:
[1, 7, 3]
[7, 4, 5]
[3, 5, 6]
It is symmetric

Matrix:
[1, 2, 0]
[3, 4, 5]
[0, 5, 6]
Not symmetric: matrix[0][1] is 2 but matrix[1][0] is 3

How it works

  1. The function compares matrix[i][j] with its mirror entry matrix[j][i].
  2. Only the entries above the diagonal need checking, because j starts at i + 1; each one is compared with its partner below the diagonal.
  3. At the first pair that differs, the function returns its position, and if every pair matches it returns None.
  4. In the second matrix, row 0 has a 2 where row 1 has a 3, so it is not symmetric.
  5. Only square matrices can be symmetric, because the transpose of a non-square matrix has a different shape.

Other ways to write it

Comparing with the transpose

Comparing with the transpose
matrix = [[1, 7, 3],
[7, 4, 5],
[3, 5, 6]]
transpose = [list(row) for row in zip(*matrix)]
print("Transpose:", transpose)
print("Symmetric:", matrix == transpose)
Output
Transpose: [[1, 7, 3], [7, 4, 5], [3, 5, 6]]
Symmetric: True

zip(*matrix) gives the columns, which are the rows of the transpose, and == compares the two matrices entry by entry.

Checking for a skew-symmetric matrix

Checking for a skew-symmetric matrix
matrix = [[0, 2, -4],
[-2, 0, 5],
[4, -5, 0]]
n = len(matrix)
skew = all(matrix[i][j] == -matrix[j][i] for i in range(n) for j in range(n))
print("Skew-symmetric:", skew)
Output
Skew-symmetric: True

A skew-symmetric matrix equals the negative of its transpose, so every mirror pair has opposite signs and the diagonal is all zeros.

Try it yourself

Add a check at the start of the function so a matrix that is not square is reported as not symmetric.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises