How to multiply matrices in Python
Matrix multiplication is only possible if the column of the second matrix is equal to rows of the first. In Python, a matrix can be represented in the form of a nested list ( a list inside a list ).
Syntax
# sample code for 3x2 matrixX = [[1,2],[3,4],[5,6]]
1 of 4
Implementation
In Python, matrix multiplication can be implemented
- using nested loops
- using nested list comprehension
Using nested loops
In this, for loops are used to compute the resultant matrix. This method becomes computationally expensive if the order of matrices increases.
Example code
# Program to multiply two matrices using nested loops# 3x2 matrixX = [ [1,2],[3,4],[4,5] ]# 2x3 matrixY = [ [1,2,3],[4,5,6] ]# resultant matrixresult = [ [0,0,0],[0,0,0],[0,0,0] ]my_list = []# iterating rows of X matrixfor i in range( len(X) ):# iterating columns of Y matrixfor j in range(len(Y[0])):# iterating rows of Y matrixfor k in range(len(Y)):result[i][j] += X[i][k] * Y[k][j]for r in result:print(r)
Using nested list comprehension
List comprehension is very useful when creating new lists from other iterables. This method is used to iterate over each element for the given expression.
Example code
# Program to multiply two matrices using list comprehension# 3x2 matrixX = [ [1,2],[3,4],[4,5] ]# 2x3 matrixY = [ [1,2,3],[4,5,6] ]# resultant matrixresultant = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in X]# printing matrix.for x in resultant:print(x)
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved