# How to add values of same index in two different lists into one list

121
February 09, 2021, at 07:20 AM

So I have two lists with different values in them,

list1 = [10, 11, 14, 14, 14, 13, 9]
list2 = [2, 3, 4, 3, 2, 2, 1]

and I was wondering on how I would add the sums of the values in each list into one list so it outputs this:

output = [12, 14, 18, 17, 16, 16, 15, 10]

The most straight forward solution would be to initialize the output list, iterate over the values in list1 and list2 using zip, and add their sum to output:

output = []
for item1, item2 in zip(list1, list2):
output.append(item1 + item2)

You can simplify this into a list comprehension like so:

output = [item1 + item2 for item1, item2 in zip(list1, list2)]

A list comprehension is a nice way to accomplish this.

output = [x + y for x, y in zip(list1, list2)]

With numpy you can easily sum arrays.

import numpy
list1 = numpy.array([10, 11, 14, 14, 14, 13, 9])
list2 = numpy.array([2, 3, 4, 3, 2, 2, 1])
output = list1 + list2

list 3 = list1 + list 2 Thank me later!

POPULAR ONLINE

### trying to backup(activation startup thing) data and apps from a phone with broken unusable screen(optimo g7 maxx) [closed]

Want to improve this question? Update the question so it's on-topic for Stack Overflow

126

### exclude a file from gulp compilation

I have a gulp file that looks like this,

111

### Remove row if value equal to [duplicate]

I am trying to remove all the rows that don't have the value '2A' or '2B' but whenever I execute the code it deletes every row except the first one

135

### Hello i need in update query ON DUPLICATE KEY UPDATE or IGNORE somthing like this AND checkin<>(checkout-interval 7 hour) [closed]

Want to improve this question? Add details and clarify the problem by editing this post

158