How to add the contents of two tuples (or lists)?

I already had this problem several times that I could not find a good solution to add the contents of two tuples together. Something that does:

a = (1, 2)
b = (3, 4)
c = (a[0]+b[0], a[1]+b[1])

I think I saw the syntax to do this only once, but I don’t remember how to do it.

+3
source share
3 answers

This also works:

>>> a = (1,2)
>>> b = (3,4)
>>> c = map(sum, zip(a,b))
>>> c
[4, 6]

It should work with any number of lists containing any number of numbers.

+3
source

One liner:

map(lambda x, y: x+ y, a, b)

I believe that this is the most effective way. You can also import operator.addto avoid the lambda function. For me, I prefer a cleaner global namespace.

+1
source

With understanding of the generator:

a = (1, 2)
b = (3, 4)
result = [x + y for x, y in zip(a, b)]

[4, 6]

0
source

All Articles