2

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.

Jacob Birkett
  • 1,927
  • 3
  • 24
  • 49

1 Answers1

8

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]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102