Reputation: 109
i'm new to python,so i'm sorry if this is a silly question. This is a legit program for matrix multiplication but i don't understand why it's throwing the error list index out of range for my input?
def matmult(a,b):
product=[[0 for i in range(len(a))] for j in range(len(b[0]))]
for i in range(len(a)):
for j in range(len(b[0])):
for k in range(len(b)):
product[i][j]+=a[i][k]*b[k][j]
return product
matmult([[1,1]],[[3,4],[5,6]])
Upvotes: 1
Views: 1027
Reputation: 536
It's because of product=[]
. The product list is empty but you are indexing it. That is throwing the IndexError: list index out of range
error
Do this instead
product = [[0 for i in range(len(b[0]))] for j in range(len(a))]
This will pre-allocate space for the product so that you can index it
Upvotes: 1