Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading