I have the following two lists:
JavaScript
x
3
1
first = [1,2,3,4,5]
2
second = [6,7,8,9,10]
3
Now I want to add the items from both of these lists into a new list.
output should be
JavaScript
1
2
1
third = [7,9,11,13,15]
2
Advertisement
Answer
The zip
function is useful here, used with a list comprehension.
JavaScript
1
2
1
[x + y for x, y in zip(first, second)]
2
If you have a list of lists (instead of just two lists):
JavaScript
1
4
1
lists_of_lists = [[1, 2, 3], [4, 5, 6]]
2
[sum(x) for x in zip(*lists_of_lists)]
3
# -> [5, 7, 9]
4