# Concise vector adding in Python?

## Concise vector adding in Python?

If you need efficient vector arithmetic, try Numpy.

``````>>> import numpy
>>> a=numpy.array([0,1,2])
>>> b=numpy.array([3,4,5])
>>> a+b
array([3, 5, 7])
>>>
``````

Or (thanks, Andrew Jaffe),

``````>>> a += b
>>> a
array([3, 5, 7])
>>>
``````

I dont think you will find a faster solution than the 3 sums proposed in the question. The advantages of numpy are visible with larger vectors, and also if you need other operators. numpy is specially useful with matrixes, witch are trick to do with python lists.

Still, yet another way to do it 😀

``````In : a = [1,2,3]

In : b = [2,3,4]

In : map(sum, zip(a,b))
Out: [3, 5, 7]
``````

Edit: you can also use the izip from itertools, a generator version of zip

``````In : from itertools import izip

In : map(sum, izip(a,b))
Out: [3, 5, 7]
``````

#### Concise vector adding in Python?

While Numeric is excellent, and list-comprehension solutions OK if you actually wanted to create a new list, Im surprised nobody suggested the one obvious way to do it — a simple `for` loop! Best:

``````for i, bi in enumerate(b): a[i] += bi
``````

Also OK, kinda sorta:

``````for i in xrange(len(a)): a[i] += b[i]
``````