This post shows how to multiply two matrices in Python using nested loops — a classic programming exercise that tests your understanding of nested iteration and 2D lists.

Multiply two matrices in Python:

Explanation:
Matrix multiplication works by taking the dot product of each row of the first matrix with each column of the second. We use three nested loops: one for the result row, one for the result column, and one to sum the products.


Python Program to Multiply Two Matrices

A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]

result = [[0, 0], [0, 0]]

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]

print("Resultant matrix:")
for row in result:
    print(row)

Output:

Resultant matrix:
[19, 22]
[43, 50]

See more array and matrix-based interview problems in our Interview Prep section.