Input: two lists (list1, list2) of equal length
Output: one list (result) of the same length, such that:
result[i] = list1[i] + list2[i]
Is there any concise way to do that? Or is this the best:
# Python 3
assert len(list1) == len(list2)
result = [list1[i] + list2[i] for i in range(len(list1))]
Element-wise addition of two lists basically means adding the first element of list1 and the first element of list2 and so on. There are several methods that perform this operation. Every method has its own uniqueness. Some of them work on unequal lengths while some works on lists of equal lengths.
You can use the builtin zip function, or you can also use do it mapping the two lists over the add operator. Like this:
from operator import add
map(add, list1,list2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With