180

I have the following two lists:

first = [1,2,3,4,5]
second = [6,7,8,9,10]

Now I want to add the items from both of these lists into a new list.

output should be

third = [7,9,11,13,15]
Community
  • 1
  • 1
Prashant Gaur
  • 9,540
  • 10
  • 49
  • 71
  • Does this answer your question? [Element-wise addition of 2 lists?](https://stackoverflow.com/questions/18713321/element-wise-addition-of-2-lists) – Abdul Aziz Barkat Jan 23 '23 at 16:08

23 Answers23

285

The zip function is useful here, used with a list comprehension.

[x + y for x, y in zip(first, second)]

If you have a list of lists (instead of just two lists):

lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]
tom
  • 18,953
  • 4
  • 35
  • 35
  • 2
    just curious how would zip() handles if array lengths for different? i.e what does zip returns for different array lengths and how would that affect the operation for x + y – ealeon Oct 24 '15 at 15:00
  • 9
    @ealeon: The "zipping" stops when the shortest iterable is exhausted. So if `first` is length 10 and `second` is length 6, the result of zipping the iterables will be length 6. – tom Oct 27 '15 at 17:12
  • Is there a way to do this when you don't know the number of lists? – traggatmot Jun 03 '16 at 05:07
  • @traggatmot: `>>> lists_of_lists = [[1, 2, 3], [4, 5, 6]]` `>>> [sum(x) for x in zip(*lists_of_lists)]` `[5, 7, 9]` – tom Jun 03 '16 at 23:34
54

From docs

import operator
list(map(operator.add, first,second))
Ameet Deshpande
  • 496
  • 8
  • 22
Thai Tran
  • 9,815
  • 7
  • 43
  • 64
53

Default behavior in numpy.add (numpy.subtract, etc) is element-wise:

import numpy as np
np.add(first, second)

which outputs

array([7,9,11,13,15])
mirekphd
  • 4,799
  • 3
  • 38
  • 59
user3582790
  • 639
  • 5
  • 2
  • 4
    use np.add(first, second).tolist() to get the result in a list – talekeDskobeDa Feb 04 '19 at 16:15
  • If `first` and `second` are np arrays you can just do `first + second`. And if you want to save the result in first, you can also do: `first += second`. – Puco4 Sep 21 '20 at 15:57
35

Assuming both lists a and b have same length, you do not need zip, numpy or anything else.

Python 2.x and 3.x:

[a[i]+b[i] for i in range(len(a))]
maro
  • 473
  • 4
  • 11
  • 30
math
  • 8,514
  • 10
  • 53
  • 61
13

Try the following code:

first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))
kenorb
  • 155,785
  • 88
  • 678
  • 743
  • +1 for this compact and self explanatory solution. It's worth noting that this works for more than 2 lists as well: `map(sum, zip(first, second, third, fourth, ...))` – Johan Dettmar Oct 05 '18 at 20:54
11

This extends itself to any number of lists:

[sum(sublist) for sublist in itertools.izip(*myListOfLists)]

In your case, myListOfLists would be [first, second]

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
6

The easy way and fast way to do this is:

three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

Alternatively, you can use numpy sum:

from numpy import sum
three = sum([first,second], axis=0) # array([7,9,11,13,15])
Thiru
  • 3,293
  • 7
  • 35
  • 52
6
first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
three = list(map(sum, first, second))
print(three)



# Output 
[7, 9, 11, 13, 15]
KetZoomer
  • 2,701
  • 3
  • 15
  • 43
Anurag Misra
  • 1,516
  • 18
  • 24
6

one-liner solution

list(map(lambda x,y: x+y, a,b))
Shadowman
  • 61
  • 1
  • 4
3

If you have an unknown number of lists of the same length, you can use the below function.

Here the *args accepts a variable number of list arguments (but only sums the same number of elements in each). The * is used again to unpack the elements in each of the lists.

def sum_lists(*args):
    return list(map(sum, zip(*args)))

a = [1,2,3]
b = [1,2,3]  

sum_lists(a,b)

Output:

[2, 4, 6]

Or with 3 lists

sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])

Output:

[19, 19, 19, 19, 19]
Coffee and Code
  • 885
  • 14
  • 16
2

My answer is repeated with Thiru's that answered it in Mar 17 at 9:25.

It was simpler and quicker, here are his solutions:

The easy way and fast way to do this is:

 three = [sum(i) for i in zip(first,second)] # [7,9,11,13,15]

Alternatively, you can use numpy sum:

 from numpy import sum
 three = sum([first,second], axis=0) # array([7,9,11,13,15])

You need numpy!

numpy array could do some operation like vectors
import numpy as np
a = [1,2,3,4,5]
b = [6,7,8,9,10]
c = list(np.array(a) + np.array(b))
print c
# [7, 9, 11, 13, 15]
Piece
  • 21
  • 2
2

What if you have list with different length, then you can try something like this (using zip_longest)

from itertools import zip_longest  # izip_longest for python2.x

l1 = [1, 2, 3]
l2 = [4, 5, 6, 7]

>>> list(map(sum, zip_longest(l1, l2, fillvalue=0)))
[5, 7, 9, 7]
mohammed wazeem
  • 1,310
  • 1
  • 10
  • 26
1

You can use zip(), which will "interleave" the two arrays together, and then map(), which will apply a function to each element in an iterable:

>>> a = [1,2,3,4,5]
>>> b = [6,7,8,9,10]
>>> zip(a, b)
[(1, 6), (2, 7), (3, 8), (4, 9), (5, 10)]
>>> map(lambda x: x[0] + x[1], zip(a, b))
[7, 9, 11, 13, 15]
cdhowie
  • 158,093
  • 24
  • 286
  • 300
1

Here is another way to do it. We make use of the internal __add__ function of python:

class SumList(object):
    def __init__(self, this_list):
        self.mylist = this_list

    def __add__(self, other):
        new_list = []
        zipped_list = zip(self.mylist, other.mylist)
        for item in zipped_list:
            new_list.append(item[0] + item[1])
        return SumList(new_list)

    def __repr__(self):
        return str(self.mylist)

list1 = SumList([1,2,3,4,5])
list2 = SumList([10,20,30,40,50])
sum_list1_list2 = list1 + list2
print(sum_list1_list2)

Output

[11, 22, 33, 44, 55]
TrakJohnson
  • 1,755
  • 2
  • 18
  • 31
Stryker
  • 5,732
  • 1
  • 57
  • 70
1

If you want to add also the rest of the values in the lists you can use this (this is working in Python3.5)

def addVectors(v1, v2):
    sum = [x + y for x, y in zip(v1, v2)]
    if not len(v1) >= len(v2):
        sum += v2[len(v1):]
    else:
        sum += v1[len(v2):]

    return sum


#for testing 
if __name__=='__main__':
    a = [1, 2]
    b = [1, 2, 3, 4]
    print(a)
    print(b)
    print(addVectors(a,b))
christianAV
  • 149
  • 1
  • 4
1
    first = [1,2,3,4,5]
    second = [6,7,8,9,10]
    #one way
    third = [x + y for x, y in zip(first, second)]
    print("third" , third) 
    #otherway
    fourth = []
    for i,j in zip(first,second):
        global fourth
        fourth.append(i + j)
    print("fourth" , fourth )
#third [7, 9, 11, 13, 15]
#fourth [7, 9, 11, 13, 15]
1

Here is another way to do it.It is working fine for me .

N=int(input())
num1 = list(map(int, input().split()))
num2 = list(map(int, input().split()))
sum=[]

for i in range(0,N):
  sum.append(num1[i]+num2[i])

for element in sum:
  print(element, end=" ")

print("")
Agney
  • 18,522
  • 7
  • 57
  • 75
1
j = min(len(l1), len(l2))
l3 = [l1[i]+l2[i] for i in range(j)]
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • 1
    While this code snippet may be the solution, [including an explanation](https://meta.stackexchange.com/questions/114762/explaining-entirely-%E2%80%8C%E2%80%8Bcode-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Narendra Jadhav Jul 21 '18 at 05:53
1

If you consider your lists as numpy array, then you need to easily sum them:

import numpy as np

third = np.array(first) + np.array(second)

print third

[7, 9, 11, 13, 15]
Radvin
  • 143
  • 4
  • 10
0

Perhaps the simplest approach:

first = [1,2,3,4,5]
second = [6,7,8,9,10]
three=[]

for i in range(0,5):
    three.append(first[i]+second[i])

print(three)
0
first = [1,2,3,4,5]
second = [6,7,8,9,10]
third=[]
for i,j in zip(first,second):
    t=i+j
    third.append(t)
print("Third List=",third)

output -- Third List= [7, 9, 11, 13, 15]
  • Please describe this code and why you think it solves the problem – user16217248 Sep 18 '22 at 04:25
  • Please don't post code-only answers. The main audience, future readers, will be grateful to see explained *why* this answers the question instead of having to infer it from the code. Also, since this is an old question, please explain how it complements all other answers. – Gert Arnold Sep 19 '22 at 19:06
0

In this question your code gets two lists of molecular weights.

Print:

The second lowest molecular weight for each list (2 numbers) The average molecular weight for the two lists together (single number) Make a new list that includes all the elements from both lists, except for the maximum and minimum values (all values from the two list except 2 values). Then sort this list and print it.

Note: the number of elements in each list is not fixed.

Variables names: mws1, mws2 You may define additional variables in your code if needed. See example of the output.

An example for the output (mws1 = [71, 88, 90], mws2 = [77, 5, 24, 65]): Second lowest of first list: 88 Second lowest of second list: 24 Average of merged lists: 60.0 Sorted values from both lists, excluding extreme values: [24, 65, 71, 77, 88]

Another example for the output (num = mws1 = [26, 34, 14, 66, 78], mws2 = [98, 15, 88]): Second lowest of first list: 26 Second lowest of second list: 88 Average of merged lists: 52.375 Sorted values from both lists, excluding extreme values: [15, 26, 34, 66, 78, 88]

Another example for the output (mws1 = [10, 53, 70, 1], mws2 = [22, 27]): Second lowest of first list: 10 Second lowest of second list: 27 Average of merged lists: 30.5 Sorted values from both lists, excluding extreme values: [10, 22, 27, 53]

-2

You can use this method but it will work only if both the list are of the same size:

first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
third = []

a = len(first)
b = int(0)
while True:
    x = first[b]
    y = second[b]
    ans = x + y
    third.append(ans)
    b = b + 1
    if b == a:
        break

print third
HelloUni
  • 448
  • 2
  • 5
  • 10