3

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.

0

1 Answer 1

10

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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.