Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the sum of matching components in two lists

Tags:

python

list

sum

I have two lists:

A = [1, 2, 3, 4, 5]
B = [6, 7, 8, 9, 10]

And I need to be able to find the sum of the nth terms from both lists i.e. 1+6, 2+7, 3+8 etc

Could someone please tell me how to refer to items in both lists at the same time?

I read somewhere that I could do Sum = a[i] + b[i] but I'm not convinced on how that would work.

like image 967
George Burrows Avatar asked Nov 27 '22 18:11

George Burrows


1 Answers

>>> import operator
>>> map(operator.add, A, B)
[7, 9, 11, 13, 15]

just to demonstrate Pythons elegance :-)

like image 183
jazz Avatar answered Dec 10 '22 09:12

jazz