-5

I've defined 2 lists, n1 and n2:

In [1]: n1=[1,2,3]

In [2]: n2=[4,5,6]

In [3]: n1+n2
Out[3]: [1, 2, 3, 4, 5, 6]

In [4]: n1+=n2

In [5]: n1
Out[5]: [1, 2, 3, 4, 5, 6]

Well, what I expected to do is to get a new list: n3=[5,7,9] as summary of each elements in n1 and n2.

I don't wish to write a for loop to do this routine job. Does python operator or library support a one-shot call to do this?

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
Troskyvs
  • 6,313
  • 4
  • 38
  • 91
  • 3
    See [here](http://stackoverflow.com/questions/18713321/element-wise-addition-of-2-lists-in-python), [here](http://stackoverflow.com/questions/845112/concise-vector-adding-in-python), [here](http://stackoverflow.com/questions/14050824/add-sum-of-values-of-two-lists-into-new-list), and probably lots more. – TigerhawkT3 Dec 24 '16 at 10:23

3 Answers3

1

I don't wish to write a for loop to do this routine job. Does python operator or library support a one-shot call to do this?

Python does not support it natively, but you can use the library NumPy:

import numpy as np

n1 = np.array([1, 2, 3])
n2 = np.array([4, 5, 6])

n3 = n1 + n2

Alternatively, you can use list comprehension and zip():

n3 = [x + y for x, y in zip(n1, n2)]
Delgan
  • 16,542
  • 9
  • 83
  • 127
1
[x + y for x, y in zip(n1, n2)]
[n1[i] + n2[i] for i in range(len(n1))]
map(int.__add__, n1, n2)
Alex Hall
  • 33,530
  • 5
  • 49
  • 82
0

No, there is no one-shot command for that. Adding elements in two lists is not a common operation. You can't avoid a loop here.

Use zip() and a list comprehension:

[a + b for a, b in zip(n1, n2)]

Alternatively, use numpy arrays:

from numpy import array

n3 = array(n1) + array(n2)
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187