The Python Oracle

Add SUM of values of two LISTS into new LIST

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Romantic Lands Beckon

--

Chapters
00:00 Question
00:24 Accepted answer (Score 280)
00:48 Answer 2 (Score 54)
01:00 Answer 3 (Score 51)
01:20 Answer 4 (Score 35)
01:41 Thank you

--

Full question
https://stackoverflow.com/questions/1405...

Answer 1 links:
[docs]: https://docs.python.org/2/library/operat...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #sum

#avk47



ACCEPTED ANSWER

Score 288


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]



ANSWER 2

Score 57


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])



ANSWER 3

Score 55


From docs

import operator
list(map(operator.add, first,second))



ANSWER 4

Score 36


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))]