'Add together lists of tuples

I have two lists of integers:

xList = [(1, 2), (3,4)]
yList = [(5, 6), (7, 8)]

I want to add the first element of xList to the first element of yList etc so that the output is as follows

[(6, 8), (10, 12)]

Any ideas that I can try using numpy or otherwise?



Solution 1:[1]

For a pure-Python approach you can use operator.add(a, b) (returns a + b) from the operator module combined with the built-in functions map(function, iterable, ...) and zip(*iterables, strict=False). The map function "[r]eturn[s] an iterator that applies function to every item of iterable, yielding the results" and the zip function iterates over several iterables in parallel, successively yielding tuples of these elements.

import operator

xList = [(1, 2), (3,4)]
yList = [(5, 6), (7, 8)]

res = [tuple(map(operator.add, a, b)) for a, b in zip(xList, yList)]
print(res)

Output

[(6, 8), (10, 12)]

Solution 2:[2]

Using a list comprehension:

out = [tuple(map(sum, zip(*x))) for x in zip(xList, yList)]

Output:

[(6, 8), (10, 12)]

generalization

This works independently of the number of input lists. For more lists:

lists = [wList, xList, yList, zList]

out = [tuple(map(sum, zip(*x))) for x in zip(*lists)]
input of uneven size

Use itertools.zip_longest:

xList = [(1, 2), (3,4)]
yList = [(5, 6), (7, 8)]
zList = [(1,1)]

from itertools import zip_longest
lists = [xList, yList, zList]
out = [tuple(map(sum, zip(*x)))
       for x in zip_longest(*lists, fillvalue=(0,0))]

Output:

[(7, 9), (10, 12)]

Solution 3:[3]

[(a[0] + b[0], a[1] + b[1]) for a, b in zip(xList, yList)]

Solution 4:[4]

x = np.array(xList)
y = np.array(yList)
print(x + y)

Output:

array([[ 6,  8],
       [10, 12]])

To make your exact desired output, though I doubt it'll matter:

print([*map(tuple, (x + y))])
...
[(6, 8), (10, 12)]

Solution 5:[5]

numpy is overkill for this problem. All you need is zip() and a list comprehension:

[(x1 + y1, x2 + y2) for (x1, x2), (y1, y2) in zip(xList, yList)]

This outputs:

[(6, 8), (10, 12)]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 oda
Solution 2
Solution 3 Jacob
Solution 4
Solution 5