Python  

Matrix Multiplication in Python

Introduction

Matrix multiplication is a fundamental concept in programming, mathematics, and data science. In Python, matrix multiplication is widely used for machine learning, image processing, scientific computing, and data analytics. Knowing how to perform it efficiently can help you build faster and more optimized applications.

What Is Matrix Multiplication?

Matrix multiplication combines two matrices to form a new one by taking the dot product of rows and columns. For example, if Matrix A is of size (2×3) and Matrix B is of size (3×2), then the result Matrix C = A × B will be of size (2×2).

Mathematically
[ C[i][j] = Σ (A[i][k] × B[k][j]) ]

In simpler terms, each element of the new matrix is formed by multiplying and summing corresponding elements from rows of A and columns of B.

Method 1. Using Nested Loops (Manual Approach)

This is the most basic method and helps you understand the underlying process.

A = [[1, 2, 3], [4, 5, 6]]
B = [[7, 8], [9, 10], [11, 12]]

# Initialize result matrix with zeros
result = [[0 for _ in range(len(B[0]))] for _ in range(len(A))]

# Matrix multiplication logic
for i in range(len(A)):
    for j in range(len(B[0])):
        for k in range(len(B)):
            result[i][j] += A[i][k] * B[k][j]

for r in result:
    print(r)

Output

[58, 64]
[139, 154]

✅ Easy to understand but not efficient for large matrices.

Method 2. Using List Comprehension

A shorter and cleaner approach using Python’s list comprehension:

A = [[1, 2, 3], [4, 5, 6]]
B = [[7, 8], [9, 10], [11, 12]]

result = [[sum(a*b for a, b in zip(A_row, B_col)) for B_col in zip(*B)] for A_row in A]

for row in result:
    print(row)

Explanation

  • zip(*B) transposes matrix B.

  • The sum(a*b...) computes dot products directly.

✅ More Pythonic than nested loops, but still slower than NumPy for large datasets.

Method 3. Using NumPy (Recommended)

NumPy is the most efficient way to perform matrix multiplication in Python.

import numpy as np

A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([[7, 8], [9, 10], [11, 12]])

# Using np.dot()
result = np.dot(A, B)
print(result)

# Or simply use the @ operator
result2 = A @ B
print(result2)

Output

[[ 58  64]
 [139 154]]

✅ Fast, optimized, and perfect for scientific or machine learning applications.

Method 4. Using np.matmul()

np.matmul() is another NumPy function that performs matrix multiplication efficiently.

import numpy as np

A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([[7, 8], [9, 10], [11, 12]])

result = np.matmul(A, B)
print(result)

This method behaves similarly to np.dot() for 2D arrays but supports higher-dimensional tensor operations as well.

Common Mistakes to Avoid

  • ❌ Using the * operator for matrix multiplication — it performs element-wise multiplication.

  • ❌ Mismatched dimensions between matrices.

  • ❌ Forgetting to convert Python lists to NumPy arrays before using NumPy functions.

Comparison Table: Loop vs List Comprehension vs NumPy

MethodDescriptionTime ComplexityTypical SpeedWhen to Use
Nested LoopsBasic triple loop logicO(n³)Slow for large matricesLearning / small examples
List ComprehensionCleaner and shorter syntaxO(n³)Slightly faster than loopsSmall scripts / readability
NumPy dot / @ / matmulUses optimized BLAS librariesO(n³) but highly optimizedFastest (suitable for big data)Production / data science / ML

Performance Comparison (Loops vs NumPy)

Matrix SizeLoops (Approx Time)NumPy (Approx Time)
50×5010–100 ms0.5–5 ms
200×2001–5 s10–100 ms
1000×1000> 2 minutes0.5–3 s

✅ NumPy is hundreds of times faster than plain Python loops for large matrices due to optimized C/Fortran code and SIMD acceleration.

Bonus. Benchmark Script

You can test performance on your own machine:

import numpy as np, time

size = 500
A = np.random.rand(size, size)
B = np.random.rand(size, size)

# NumPy multiplication
start = time.time()
np.dot(A, B)
print("NumPy Time:", round(time.time() - start, 4), "seconds")

# Python loops
A_list, B_list = A.tolist(), B.tolist()
result = [[0]*size for _ in range(size)]
start = time.time()
for i in range(size):
    for j in range(size):
        for k in range(size):
            result[i][j] += A_list[i][k] * B_list[k][j]
print("Loop Time:", round(time.time() - start, 4), "seconds")

Summary

Matrix multiplication is a key skill in Python programming, especially for data processing and machine learning. While nested loops and list comprehensions are useful for understanding, NumPy provides the fastest and most reliable way to perform matrix operations in real-world scenarios.

Key Takeaways

  • Always check matrix dimension compatibility.

  • Use np.dot() or the @ operator for efficient multiplication.

  • NumPy’s performance scales extremely well for large datasets.

By mastering matrix multiplication in Python, you’re one step closer to building efficient, data-driven applications and mastering numerical computing!