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 :

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

Leave a Reply