KermitTheFrog
KermitTheFrog

Reputation: 145

Sum of every element in a list

So i have a list:

list1 = [[1, 3, 6, 8, 9, 9, 12], [1, 2, 3, 2, 1, 0, 3, 3]]

but you can also split it into two lists, if it make it any easier. All i have to do is sum every digit with every other digit. Like you know first row:

1+1, 1+2, 1+3, 1+2, 1+1...

second:

3+1... etc.

first = [1, 3, 6, 8, 9, 9, 12]
second = [1, 2, 3, 2, 1, 0, 3, 3]

w = [x + y for x, y in zip(first, second)]

I was trying to do it in this way. But it doesn't work*, any ideas?

*i mean its summing in a wrong way, instead of every possible digits with every possible, just the first one in 1st list with 1st in second list.

Upvotes: 2

Views: 158

Answers (2)

mhhabib
mhhabib

Reputation: 3121

You can do it using itertools to get all possible pair then make a pair of sum list

import itertools
first = [1, 3, 6, 8, 9, 9, 12]
second = [1, 2, 3, 2, 1, 0, 3, 3]

res = itertools.product(first, second)
ress = [sum(pair) for pair in res]
print(ress)

Upvotes: 2

trincot
trincot

Reputation: 350272

zip is getting only pairs that sit at the same index. You should instead have a double loop:

[x + y for x in first for y in second]

Upvotes: 3

Related Questions