party911
party911

Reputation: 43

Sum lists in python

I got two lists:

list_1 = [a1, a2, a3, ... a36]
list_2 = [b1, b2, b3,... b12]

how can i get the sum of this two lists, according to an algorithm such as

a1 + b1, a1+b2, a1+b3,... , a1+b12 
then 
a2+b1, a2+b2, a2+b3,..., a2+b12

Upvotes: 0

Views: 110

Answers (3)

mahesh
mahesh

Reputation: 1098

This simple code would work too:

list_1 = [1, 2, 3, 4]
list_2 = [5, 6, 7]
list_3 = [a+b for a in list_1 for b in list_2] # Adding them up pairwise

Now, list_3 would contain all the sums.

Upvotes: 1

zipa
zipa

Reputation: 27869

From your question you seem to want this:

list_1 = [1,2,3]
list_2 = [4,5,6]

list_2_sum = sum(list_2)

[i + list_2_sum for i in list_1]
#[16, 17, 18]

Or if you list_1 is longer:

list_1 = [1, 2, 3, 4]
list_2 = [4, 5, 6]

list_2_sum = sum(list_2)

[x + list_2_sum for x, _ in zip(list_1, list_2)]
#[16, 17, 18]

Upvotes: 0

Rakesh
Rakesh

Reputation: 82755

Use itertools.product

Ex:

from itertools import product


list_1 = [1,2,3]
list_2 = [4,5,6]

print([sum(i) for i in product(list_1, list_2)])

Output:

[5, 6, 7, 6, 7, 8, 7, 8, 9]

Upvotes: 1

Related Questions