How to sum vectors represented by tuples in Python?

Let's say I have to sum 2 vectors of n-dimensions. What is the pytonic way of adding them directly?

For example in R^3, but without being limited to R^3,

a = (123.45, 23.45, 1.0)
b = (45.678, 56.78, 5.0)

(Get (169.128, 80.23, 6.0))

 7
Author: Fabián Heredia Montiel, 2015-12-03

6 answers

If you try the obvious, you get a generator:

>>> (sum(x) for x in zip(a, b))
<generator object <genexpr> at 0x7faf248e20f8>

So you can convert it to tuple directly:

>>> tuple(sum(x) for x in zip(a, b))
(169.128, 80.23, 6.0)

In any case, I recommend that you instead use NumPy :

>>> import numpy as np
>>> a = np.array((123.45, 23.45, 1.0))
>>> b = np.array((45.678, 56.78, 5.0))
>>> a + b
array([ 169.128,   80.23 ,    6.   ])
 12
Author: astrojuanlu, 2015-12-06 03:18:53

Another Way using the modules operator and itertools:

from itertools import izip, starmap
from operator import add

add_tuples = lambda a,b: tuple(starmap(add, izip(a, b)))

Using the example provided:

>>> a = (123.45, 23.45, 1.0)
>>> b = (45.678, 56.78, 5.0)
>>> print(add_tuples(a, b))
(169.128, 80.23, 6.0)
>>>
 2
Author: Euribates, 2015-12-17 15:11:16

Other form pythonica :

a = (123.45, 23.45, 1.0)
b = (45.678, 56.78, 5.0)

c = tuple(map(lambda x, y: x + y, a, b))
print(c)

map it takes one element from each of the iterables passed to it, which allows you to save the zip.

In Python 3.x, map returns a generator.

In Python 2.X could be used itertools.imap instead of map to always have a consistent result and not generate an intermediate list.

Result

(169.128, 80.23, 6.0)
 2
Author: mementum, 2016-01-13 11:33:51

Try with:

S = [i+j for i,j in zip(a,b)]
 2
Author: Gaby Du, 2016-02-15 20:55:51

The programming language Python is one of the most widely used in the field of science and education and that is due to their libraries and APIs specific for all things related to the scientific computing, I recommend you go to SciPy and check out this large gallery of libraries very interesting among which, is NumPy, which you recommended, and Matplotlib which is also very useful for what you want to do, it is only a matter do a little research in their documentation and see which one comes closest to what you want to do.

Remember that one of the advantages of Python is the large number of libraries that solve many of the problems we face in the educational and labor field. Whenever you have to do something specific surely someone already create a library that by using it will most likely help you minimize the time to solve the problem.

 1
Author: Omar Gonzalez, 2019-07-08 06:22:13

In Principle:

>>> map(sum, zip(a, b))

Now in python3 you will get a generator, so if you want to get a tuple or a list:

>>> tuple(map(sum, zip(a, b))
 0
Author: José Miguel SA, 2016-01-13 16:36:38