Reputation: 131
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.
Upvotes: 0
Views: 274
Reputation: 77837
Do the size check and then build the result directly with a doubly-nested list comprehension. Numpy is better, but if you want to avoid an import, this will do.
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
if len(X) == len(Y) and len(X[0]) == len(Y[0]):
result = [[X[i][j] + Y[i][j] for j in range(len(X[0]))]
for i in range(len(X))]
print result
Output:
[[17, 15, 4], [10, 12, 9], [11, 13, 18]]
Upvotes: 1