Perform Matrix Addition in Python

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

What you’ll learn

  • The matrix rule C[i][j] = A[i][j] + B[i][j] for matrices with the same shape.
  • How to implement reusable add and print functions with nested loops.
  • Two complete Python programs (3x3 and 2x2) plus a live preview using the same sample data.

Overview

Matrix addition combines matching cells only. In Python, matrices are often represented as list-of-lists, and we compute the result using two loops: one for rows and one for columns.

Two programs

A clear 3x3 version and a compact 2x2 version.

Live preview

Try the exact sample from example 1 directly in your browser.

Interview-ready

Includes shape rules, pitfalls, complexity, and practical FAQ answers.

Prerequisites

Basic Python syntax, loops, and list indexing.

  • Know how a matrix can be stored as a list of rows, like [[1, 2], [3, 4]].
  • Be comfortable with nested loops and accessing elements by matrix[i][j].

What is matrix addition?

If A and B are both m x n matrices, then C = A + B is also m x n and each output entry is C[i][j] = A[i][j] + B[i][j].

If dimensions do not match, addition is not defined. A robust program should check this before computing.

Same shape valid addition
Different shape not defined

Formal definition

For all valid row indices i and column indices j, the sum matrix satisfies C[i][j] = A[i][j] + B[i][j]. This is the same for integer and real-valued matrices.

2x2 example

[[1, 2], [3, 4]] + [[4, 3], [2, 1]] = [[5, 5], [5, 5]] - each matching cell adds independently.

Intuition

Think of each position as a pair of numbers from the two matrices that must be combined.

A[i][j]+B[i][j] One cell
Rule
Never mix positions. Top-left adds to top-left, middle adds to middle, etc.
m*n Adds
Work
An m x n matrix has exactly m*n entries to process.

Takeaway: nested loops are not optional ceremony; they are the direct way to visit every matrix position once.

Live preview

Uses the same 3x3 sample matrices as code example 1. Click to display Matrix 1, Matrix 2, and the resultant matrix.

Matches the sample matrices in code example 1.

Live result
Press "Show 3x3 sum".

Algorithm

Goal: given two equal-sized matrices A and B, build matrix C where each cell is the sum of corresponding cells.

Check dimensions

If row or column counts differ, stop and report that addition is not possible.

Traverse with nested loops

For each row i and column j, set result[i][j] = mat1[i][j] + mat2[i][j].

Display result

Print each row on a new line to keep matrix layout clear and readable.

📜 Pseudocode

Pseudocode
function add_matrices(A, B, rows, cols):
    create matrix C of shape rows x cols
    for i from 0 to rows - 1:
        for j from 0 to cols - 1:
            C[i][j] <- A[i][j] + B[i][j]
    return C
1

Add two 3x3 matrices (program with explanation)

This program uses helper functions for addition and display. It is beginner-friendly and interview-friendly because each step is clear.

python
def add_matrices(mat1: list[list[int]], mat2: list[list[int]]) -> list[list[int]]:
    rows = len(mat1)
    cols = len(mat1[0])
    result = []
    for i in range(rows):
        row = []
        for j in range(cols):
            row.append(mat1[i][j] + mat2[i][j])
        result.append(row)
    return result

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

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

    result_matrix = add_matrices(matrix1, matrix2)

    display_matrix("Matrix 1:", matrix1)
    print()
    display_matrix("Matrix 2:", matrix2)
    print()
    display_matrix("Resultant Matrix:", result_matrix)

if __name__ == "__main__":
    main()

Explanation

The key line is mat1[i][j] + mat2[i][j]. Nested loops ensure every matching position is processed once.

for i in range(rows): for j in range(cols):

Traversal: visits all cells in row-major order.

" ".join(str(x) for x in row)

Output formatting: keeps each row readable like a matrix in console output.

2

Add two 2x2 matrices

A smaller example with the same logic. Great for quick dry-runs in interviews.

python
def add_matrices_2x2(a: list[list[int]], b: list[list[int]]) -> list[list[int]]:
    result = [[0, 0], [0, 0]]
    for i in range(2):
        for j in range(2):
            result[i][j] = a[i][j] + b[i][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 = [
        [4, 3],
        [2, 1]
    ]
    c = add_matrices_2x2(a, b)

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

if __name__ == "__main__":
    main()

Explanation

Even with fixed size 2x2, the exact same pattern works: loop over rows and columns and add matching entries.

Optimization and extensions

Large matrices. Use row-major traversal (natural list order) for cache-friendly access. For huge data, libraries like NumPy are much faster.

Dimension-safe function. Add checks for empty matrices, ragged rows, and mismatched shapes before computing.

Interview tip: first state the formula and shape condition, then write nested loops cleanly.

❓ FAQ

They must have exactly the same dimensions: same row count and same column count. Then each output cell is the sum of matching cells.
For interview-level problems, a matrix is usually a list of lists, such as [[1, 2], [3, 4]]. Each inner list is one row.
Yes. For equal-sized matrices, A + B = B + A because each pair of matching entries is added.
For an m x n matrix, we visit each entry once, so time complexity is O(m*n). Extra space is O(1) besides the output matrix.
Python integers are arbitrary precision, so normal integer overflow does not happen. But very large numbers can still make operations slower.
Because matrices are 2D. The outer loop walks rows and the inner loop walks columns, so every position (i, j) is processed exactly once.

🔄 Input / output notes

These examples use built-in matrices. In real tasks, you might read rows using input loops, parse values, validate dimensions, then pass matrices to a reusable add function.

Edge cases and pitfalls

Most matrix-addition bugs come from shape assumptions and indexing mistakes.

Shape

Mismatched dimensions

Never add matrices with different row counts or column counts.

Input

Ragged rows

In Python, one row can accidentally have fewer columns. Validate each row length first.

Index

Wrong loop bounds

Using the wrong row/column range can skip cells or raise index errors.

⏱️ Time and space complexity

OperationTimeExtra space
Add two m x n matricesO(m*n)O(1) besides the output matrix
Print an m x n matrixO(m*n)O(1)

Summary

  • Definition: C[i][j] = A[i][j] + B[i][j] only when dimensions match.
  • Code pattern: nested loops over rows and columns, plus optional print helper.
  • Complexity: linear in number of cells, m*n.
Did you know?

Matrix addition is entrywise: (A+B)ij = Aij + Bij. It is valid only when both matrices have the same number of rows and columns.

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