4

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.

2

5 Answers 5

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

just to demonstrate Pythons elegance :-)

3
  • well, this shows python's versatility, because list-comprehensions are far more elegant :-)
    – tokland
    Oct 30, 2011 at 22:07
  • Yeah, you are right: I was more thinking of easy readability: "map" the function "add" to list "A" and "B".
    – jazz
    Oct 30, 2011 at 22:10
  • This fails if A and B are of different lengths. Using zip inside of a list comprehension works well.
    – FogleBird
    Nov 15, 2013 at 23:35
13

Use a list comprehension and zip:

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

Are these questions homework? Or self-study?

1
  • Self study which I can then apply to homework, the question posted on here is an easier version, however the 'homework' isn't assessed as I'm at university. Oct 30, 2011 at 21:53
0

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

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

In Python 2, you might want to use xrange instead of range if your lists are quite large. I think that's an explicit, simple, readable, obvious way to do it, but some might differ.

If the lists might be different lengths, you have to decide how you want to handle the extra elements. Let's say you want to ignore the extra elements of whichever list is longer. Here are three ways to do it:

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 downside of using zip is that it will allocate a list of tuples, which can be a lot of memory if your lists are already large. Using for i in xrange with subscripting won't allocate all that memory, or you can use itertools.izip:

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

If you instead want to pretend the shorter list is padded 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)]
6
  • This will raise IndexError if len(A) > len(B). Oct 30, 2011 at 22:11
  • 2
    This isn't the Pythonic way to do it. Sorry. Oct 30, 2011 at 22:24
  • @TimPietzcker in the situations I am using it len(A) = len(B) for every case, but I appreciate the heads up :) Oct 30, 2011 at 22:37
  • @RaymondHettinger Do you mean this will not work? I am confused as it worked for me. Oct 30, 2011 at 22:40
  • Using zip() is preferred over approaches using indexes. The latter is normal for C and Java. The former is the Python way. Also, as Tim points out, zip() is designed to handle mismatched sequence lengths. Oct 30, 2011 at 23:05
0

Although Jazz's solution works for 2 lists, what if you have more than 2 lists? Here's a 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]
-1

Hi You can try this too:

>>>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]
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.