Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: pointwise list sum

Tags:

python

list

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))]
like image 839
max Avatar asked Apr 26 '11 09:04

max


People also ask

What is element-wise addition?

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.


1 Answers

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)
like image 105
Senthil Kumaran Avatar answered Sep 30 '22 05:09

Senthil Kumaran