Search code examples
pythonlistloopsfor-loopsummary

How to add up 2 list elements to form a new list in python, by one shot?


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?


Solution

  • [x + y for x, y in zip(n1, n2)]
    [n1[i] + n2[i] for i in range(len(n1))]
    map(int.__add__, n1, n2)