Reputation: 15
So i need to define a function, in which i get 2 lists that are 2d. The goal is to add each element to each other.
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
the result should be this:
result = [[2,4,6], [8,10,12],[14,16,18]]
So far, i built this function:
def add_matrices(list1, list2):
matrix = list1 + list2
return matrix
But im kinda stuck now, I have tried to use append and extend, but both didn't work. I have found a few solutions that required the usage of numpy, which unfortunately isn't allowed for this. Can anybody please guide me in the right direction?
Upvotes: 0
Views: 458
Reputation: 61920
One approach:
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
res = [[e1 + e2 for e1, e2 in zip(li1, li2)] for li1, li2 in zip(list1, list2)]
print(res)
Output
[[2, 4, 6], [8, 10, 12], [14, 16, 18]]
Functional alternative using map:
from operator import add
res = [list(map(add, li1, li2)) for li1, li2 in zip(list1, list2)]
print(res)
UPDATE
If required to return None
if any of the inner list do not match in length, do the following:
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
list2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
def list_sum(lst1, lst2):
if any(len(e1) != len(e2) for e1, e2 in zip(lst1, lst2)):
return None
return [[e1 + e2 for e1, e2 in zip(li1, li2)] for li1, li2 in zip(list1, list2)]
print(list_sum(list1, list2))
print(list_sum([[1, 2], [4, 5], [7, 8]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
Output
[[2, 4, 6], [8, 10, 12], [14, 16, 18]]
None
Upvotes: 2