How can I add matrices (list of lists) in python? I know that I can do this:
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
But what if the the input of the two lists have different numbers of rows or columns? I need to check first to see if the number of rows and columns are the same before adding and I'm not sure how to do this.
numpyfor this?(assert len(X) == len(Y)) and (len(X[0]) == len(Y[0]))(assuming that you know all sub-lists will be of the same length)