How to Multiply Two Matrices using Python?

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.


X = [[1,2,3],  
Y = [[10,11,12],  
result = [[0,0,0],  
# iterate through rows of X  
for i in range(len(X)):  
   for j in range(len(Y[0])):  
       for k in range(len(Y)):  
           result[i][j] += X[i][k] * Y[k][j]  
for r in result:  


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