# How to Multiply Two Matrices using Python?

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Multiplication of two matrices is possible only when number of columns in first matrix equals number of rows in second matrix.

Multiplication can be done using nested loops. Following program has two matrices x and y each with 3 rows and 3 columns. The resultant z matrix will also have 3X3 structure. Element of each row of first matrix is multiplied by corresponding element in column of second matrix.

## Example

X = [[1,2,3],
[4,5,6],
[7,8,9]]

Y = [[10,11,12],
[13,14,15],
[16,17,18]]

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

# iterate through rows of X
for i in range(len(X)):
for j in range(len(Y)):
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)  

## Output

The result:
[84, 90, 96]
[201, 216, 231]
[318, 342, 366]