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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With