Perform Matrix Multiplication in Python

Beginner
⏱️ 12 min read
📚 Updated: May 2026
🎯 2 Code Examples
Linear algebra

What you’ll learn

  • The row x column rule: each entry in AB is a dot product.
  • Why matrix multiplication needs three nested loops in the classic approach.
  • Two complete Python programs (3x3 and 2x2) plus a live preview.

Overview

Matrix multiplication is not element-wise. It combines a row from the first matrix with a column from the second matrix, then sums products.

Two programs

A full 3x3 walkthrough and a smaller 2x2 practice example.

Live preview

Run the same 3x3 sample in your browser.

Core rules

Dimension compatibility, dot products, and complexity.

Prerequisites

Nested loops, list indexing, and basic matrix terminology.

  • Know that a matrix can be stored as list-of-lists in Python.
  • You understand loops and can trace values with indices i, j, and k.

What is matrix multiplication?

If A is m x n and B is n x p, then AB exists and has size m x p. The key formula is C[i][j] = sum(A[i][k] * B[k][j]).

So each result cell is a dot product: one row from A with one column from B.

Valid sizes (m x n)(n x p) -> m x p
Not this cell-by-cell multiply

Formula

For each output entry, multiply matching row/column terms and sum them. In index form: C[i][j] = sum over k of A[i][k] * B[k][j].

Square case

When both matrices are n x n, the product is also n x n. This page shows 3x3 and 2x2 examples.

Trace one cell

In the 3x3 sample, top-left output is: 1*9 + 2*6 + 3*3 = 30.

Row dot column One result cell
k loop
Walk shared dimension and accumulate into result[i][j].

Takeaway: k connects A[i][k] with B[k][j].

Live preview

Uses the same 3x3 matrices as code example 1. Click to display both inputs and the product matrix.

Matches the Python sample values below.

Live result
Press "Show 3x3 product".

Algorithm

Goal: compute C = AB for compatible matrices.

Create zero result matrix

Initialize every result cell to zero before adding products.

Triple nested loop

For each i and j, loop over k and accumulate A[i][k] * B[k][j].

Print output

Display A, B, and C row by row for clear verification.

📜 Pseudocode

Pseudocode
function multiply(A, B):
    n <- size
    C <- n x n matrix of zeros
    for i from 0 to n - 1:
        for j from 0 to n - 1:
            for k from 0 to n - 1:
                C[i][j] <- C[i][j] + A[i][k] * B[k][j]
    return C
1

Multiply two 3x3 matrices

Classic interview-style implementation with helper functions for multiply and display.

python
N = 3

def multiply_matrices(a: list[list[int]], b: list[list[int]]) -> list[list[int]]:
    result = [[0 for _ in range(N)] for _ in range(N)]
    for i in range(N):
        for j in range(N):
            for k in range(N):
                result[i][j] += a[i][k] * b[k][j]
    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:
    first_matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
    second_matrix = [
        [9, 8, 7],
        [6, 5, 4],
        [3, 2, 1]
    ]

    result = multiply_matrices(first_matrix, second_matrix)

    print("First Matrix:")
    display_matrix(first_matrix)
    print("\nSecond Matrix:")
    display_matrix(second_matrix)
    print("\nResult Matrix:")
    display_matrix(result)

if __name__ == "__main__":
    main()

Explanation

The innermost loop computes one dot product for each result cell.

result[i][j] += a[i][k] * b[k][j]

Accumulate: add one product per k until the cell is complete.

2

Smaller 2x2 product (easy to verify)

Same logic with a smaller matrix so manual checking is easier.

python
N = 2

def multiply_matrices(a: list[list[int]], b: list[list[int]]) -> list[list[int]]:
    result = [[0 for _ in range(N)] for _ in range(N)]
    for i in range(N):
        for j in range(N):
            for k in range(N):
                result[i][j] += a[i][k] * b[k][j]
    return result

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 = [[5, 6], [7, 8]]
    r = multiply_matrices(a, b)

    print_matrix("A", a)
    print()
    print_matrix("B", b)
    print()
    print_matrix("AB", r)

if __name__ == "__main__":
    main()

Explanation

Top-left value is 1*5 + 2*7 = 19; this matches the first value in output.

Notes for larger problems

Non-square matrices. Use rowsA, colsA, and colsB with the check colsA == rowsB.

Performance. Advanced solutions use blocking and optimized libraries like NumPy for big matrices.

❓ FAQ

A must have as many columns as B has rows. If A is m x n and B is n x p, then AB is defined and its size is m x p.
No. Standard matrix multiplication uses row-column dot products. Cell-by-cell multiplication is a different operation called element-wise or Hadamard multiplication.
One loop chooses result row i, another chooses result column j, and the innermost loop accumulates sum over k: A[i][k] * B[k][j].
Each result cell is a running sum of products. It must start at zero before we add terms.
Python integers are arbitrary precision, so normal integer overflow does not happen. But very large values can increase runtime.
The classic triple-loop algorithm performs O(n^3) arithmetic operations for square matrices.

🔄 Input / output

Examples use fixed matrices in code. For custom input, parse rows into lists, validate dimensions, then run the same triple-loop logic.

Edge cases

Common beginner mistakes:

Shape

Inner dimensions mismatch

Cannot multiply unless columns of A equal rows of B.

Order

AB is not always BA

Changing order usually changes result, and sometimes makes multiplication invalid.

Logic

Forgetting zero init

If result cells do not start at zero, accumulation gives incorrect values.

⏱️ Time and space complexity

SettingTimeExtra space
Two n x n matrices, classic triple loopO(n^3)O(1) beyond output
m x n by n x pO(m*n*p)O(1) beyond output

Summary

  • Rule: C[i][j] = sum(A[i][k] * B[k][j]), with compatible dimensions.
  • Code pattern: initialize result to zeros, then use three loops.
  • Complexity: cubic for square matrices with the basic algorithm.
Did you know?

Matrix multiplication pairs rows of A with columns of B. If A is m x n and B is n x p, then AB exists and has size m x p.

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