Add SUM of values of two LISTS into new LIST
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping
--
Chapters
00:00 Add Sum Of Values Of Two Lists Into New List
00:18 Accepted Answer Score 288
00:37 Answer 2 Score 55
00:46 Answer 3 Score 57
01:02 Answer 4 Score 36
01:15 Thank you
--
Full question
https://stackoverflow.com/questions/1405...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #sum
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping
--
Chapters
00:00 Add Sum Of Values Of Two Lists Into New List
00:18 Accepted Answer Score 288
00:37 Answer 2 Score 55
00:46 Answer 3 Score 57
01:02 Answer 4 Score 36
01:15 Thank you
--
Full question
https://stackoverflow.com/questions/1405...
--
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))]