Perform Matrix Subtraction in Python

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code Examples
2D lists

What you’ll learn

  • The element-wise rule C[i][j] = A[i][j] - B[i][j] for same-sized matrices.
  • A complete 3x3 Python program and a compact 2x2 version.
  • How subtraction relates to addition: A - B = A + (-B).

Overview

Subtracting matrices means subtracting matching positions, one by one. It works only when both matrices have equal row and column counts.

Two examples

A 3x3 walkthrough and a 2x2 quick-check program.

Live preview

See the same sample subtraction done in-browser.

Negative values

Result entries can be negative, and that is normal.

Prerequisites

Basic loops and list indexing in Python.

  • Know matrix representation as list-of-lists, like [[1, 2], [3, 4]].
  • Understand that subtraction can produce negative numbers.

What is matrix subtraction?

If A and B have the same dimensions, then C = A - B where each result cell is C[i][j] = A[i][j] - B[i][j].

You can also think of it as adding the negative matrix: A + (-B).

Order matters A - B
Reverse differs B - A = -(A - B)

Live preview

Uses the same 3x3 sample as code example 1. Click to print Matrix 1, Matrix 2, and Matrix1 - Matrix2.

Matches the first Python code example below.

Live result
Press "Show 3x3 difference".

Algorithm

Goal: compute C[i][j] = A[i][j] - B[i][j] for every matrix cell.

Check dimensions

Both matrices must have same row and column counts.

Nested loops

For each i and j, assign result[i][j] = A[i][j] - B[i][j].

Display result

Print row by row for easy visual validation.

📜 Pseudocode

Pseudocode
function subtract_matrices(A, B):
    for each row i:
        for each column j:
            C[i][j] <- A[i][j] - B[i][j]
    return C
1

Subtract two 3x3 matrices (program with explanation)

subtract_matrices computes matrix1 - matrix2. Some output values are negative, which is expected.

python
def subtract_matrices(mat1: list[list[int]], mat2: list[list[int]]) -> list[list[int]]:
    result = []
    for i in range(3):
        row = []
        for j in range(3):
            row.append(mat1[i][j] - mat2[i][j])
        result.append(row)
    return result

def display_matrix(matrix: list[list[int]]) -> None:
    for row in matrix:
        print("\t".join(str(x) for x in row))

def main() -> None:
    matrix1 = [
        [5, 8, 2],
        [7, 4, 9],
        [3, 6, 1]
    ]
    matrix2 = [
        [3, 1, 7],
        [6, 9, 2],
        [8, 5, 4]
    ]

    result_matrix = subtract_matrices(matrix1, matrix2)

    print("Matrix 1:")
    display_matrix(matrix1)
    print("\nMatrix 2:")
    display_matrix(matrix2)
    print("\nResultant Matrix (Matrix1 - Matrix2):")
    display_matrix(result_matrix)

if __name__ == "__main__":
    main()

Explanation

Every result cell performs exactly one subtraction from matching positions.

2

Subtract two 2x2 matrices

Smaller matrix, same logic. Good for quick interview dry-run.

python
ROWS = 2
COLS = 2

def subtract_matrices(a: list[list[int]], b: list[list[int]]) -> list[list[int]]:
    out = [[0 for _ in range(COLS)] for _ in range(ROWS)]
    for i in range(ROWS):
        for j in range(COLS):
            out[i][j] = a[i][j] - b[i][j]
    return out

def print_matrix(title: str, m: list[list[int]]) -> None:
    print(title)
    for row in m:
        print(*row)

def main() -> None:
    a = [[1, 2], [3, 4]]
    b = [[4, 3], [2, 1]]
    c = subtract_matrices(a, b)

    print_matrix("A", a)
    print()
    print_matrix("B", b)
    print()
    print_matrix("A - B", c)

if __name__ == "__main__":
    main()

Explanation

This compact example shows both negative and positive result cells.

Notes

In-place option. You can overwrite one matrix if you no longer need original values.

Shape checks. For dynamic input, validate equal dimensions before subtraction.

❓ FAQ

Subtraction is cell-by-cell for same-sized matrices. Multiplication uses row-column dot products and follows different dimension rules.
Yes. Every A[i][j] needs a matching B[i][j], so both must have identical rows and columns.
Usually no. Subtraction is not commutative. In fact, B - A is the negative of A - B.
Yes. If A[i][j] is smaller than B[i][j], the result at that cell is negative.
Normal integer overflow does not happen with Python int because it supports arbitrary precision integers.
For an m x n matrix, each cell is processed once, so time complexity is O(m*n).

🔄 Input / output

These examples use hardcoded matrices. For user input, collect rows into lists and ensure both matrices have matching dimensions.

Edge cases

Common mistakes to avoid:

Shape

Mismatched matrices

Subtraction is valid only when dimensions are identical.

Order

Wrong operand order

A - B and B - A are different results.

⏱️ Time and space complexity

OperationTimeExtra space
Subtract two m x n matricesO(m*n)O(1) besides result matrix

Summary

  • Definition: C[i][j] = A[i][j] - B[i][j] for same-shaped matrices.
  • Code: two nested loops and one subtraction per cell.
  • Relation: A - B = A + (-B) entrywise.
Did you know?

Matrix subtraction is entrywise like addition: (A - B)ij = Aij - Bij. It is equivalent to A + (-B), and both matrices must have the same shape.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful