- Rule
- Never mix positions. Top-left adds to top-left, middle adds to middle, etc.
Perform Matrix Addition in Python
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.
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.
[[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.
- Work
- An
m x nmatrix has exactlym*nentries 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.
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
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 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.
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.
Add two 2x2 matrices
A smaller example with the same logic. Great for quick dry-runs in interviews.
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
🔄 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.
Mismatched dimensions
Never add matrices with different row counts or column counts.
Ragged rows
In Python, one row can accidentally have fewer columns. Validate each row length first.
Wrong loop bounds
Using the wrong row/column range can skip cells or raise index errors.
⏱️ Time and space complexity
| Operation | Time | Extra space |
|---|---|---|
Add two m x n matrices | O(m*n) | O(1) besides the output matrix |
Print an m x n matrix | O(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.
Matrix addition is entrywise: (A+B)ij = Aij + Bij. It is valid only when both matrices have the same number of rows and columns.
8 people found this page helpful
