JackWeir
JackWeir

Reputation: 75

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?

Upvotes: 1

Views: 65

Answers (5)

BrokenBenchmark
BrokenBenchmark

Reputation: 19223

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

Upvotes: 0

mozway
mozway

Reputation: 260300

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

Upvotes: 2

BeRT2me
BeRT2me

Reputation: 13242

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

Upvotes: 0

OTheDev
OTheDev

Reputation: 2967

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

Upvotes: 1

Jacob
Jacob

Reputation: 810

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

Upvotes: 1

Related Questions