Finding the sum of matching components in two lists

I have two lists:

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

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

Can someone tell me how to access elements in both lists at the same time?

I read somewhere that I can do Sum = a [i] + b [i], but I'm not sure how this will work.

+4
source share
5 answers

If you know that the lists will be the same length, you can do this:

 AB = [A[i] + B[i] for i in range(len(A))] 

In Python 2, you can use xrange instead of range if your lists are large enough. I think an explicit, simple, readable, obvious way , but some may differ.

If the lists can have different lengths, you need to decide how you want to handle additional elements. Let's say you want to ignore the extra elements of which list is larger. Here are three ways to do this:

 AB = [A[i] + B[i] for i in range(min(len(A), len(B)))] AB = map(sum, zip(A, B)) AB = [a + b for a, b in zip(A, B)] 

The disadvantage of using zip is that it will allocate a list of tuples, which can be a large amount of memory if your lists are already large. Using for i in xrange with a subscription will not allocate all this memory, or you can use itertools.izip :

 import itertools AB = map(sum, itertools.izip(A, B)) 

If you want to pretend that the shorter list is filled with zeros, using itertools.izip_longest is the shortest answer:

 import itertools AB = map(sum, itertools.izip_longest(A, B, fillvalue=0)) 

or

 import itertools AB = [a + b for a, b in itertools.izip_longest(A, B, fillvalue=0)] 
0
source
 >>> import operator >>> map(operator.add, A, B) [7, 9, 11, 13, 15] 

just to demonstrate Pythons elegance :-)

+15
source

Use list comprehension and zip :

 [a + b for (a,b) in zip(A,B)] 

Are these questions homework? Or self-study?

+13
source

Although the Jazz solution works for 2 lists, what if you have more than two lists? Here's the solution:

 def apply_elementwise_function(elements_in_iterables, function): elementwise_function = lambda x, y: itertools.imap(function, itertools.izip(x, y)) return reduce(elementwise_function, elements_in_iterables) a = b = c = [1, 2, 3] >>> list(apply_elementwise_function([a, b, c], sum)) [3, 6, 9] 
0
source

Hi You can also try:

 >>>a=[1,2,3,4,5] >>>b=[6,7,8,9,10] >>>c=[] >>>for i in range(0,5): c.append(a[i]+b[i]) >>> c [7, 9, 11, 13, 15] 
-1
source

All Articles