Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add values from lists of same length in Python [duplicate]

I want to add each value of two (maybe more for expand-ability) lists or tuples and return another iterable with the sums of the corresponding values.

Here are two lists filled with arbitrary values.

l1 = [90, 7, 30, 6]
l2 = [8,  2, 40, 5]

Of course, adding them with a plus operator simply concatenates.

l1 + l2 = [90, 7, 30, 6, 8, 2, 40, 5]

Is there a simple way, other than iterating through it, to add each value to the matching one of a corresponding list or tuple?

l1 + l2 = [98, 9, 70, 11]

That's what I need, and I really think there must be a simpler way than making an iteration function to do this.

Thanks.

like image 796
Jacob Birkett Avatar asked Jan 21 '26 12:01

Jacob Birkett


1 Answers

You need to use zip:

l1 = [90, 7, 30, 6]
l2 = [8,  2, 40, 5]

new = [a+b for a, b in zip(l1, l2)]

Output:

[98, 9, 70, 11]
like image 83
Ajax1234 Avatar answered Jan 24 '26 00:01

Ajax1234



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!