0

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
party911
  • 47
  • 5
  • This is unclear. Do you need just the first two iterations of this pattern? What output do you require: two lists or a list of lists? Can you provide a **[mcve]**? – jpp Nov 07 '18 at 10:53
  • Possible duplicate of [Matrix Multiplication in python?](https://stackoverflow.com/questions/10508021/matrix-multiplication-in-python) – Egalth Nov 07 '18 at 10:54

3 Answers3

1

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]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • that's the solution I even prefer over mine :) Only drawback is the need for an import and it's maybe not obvious to everyone what "product" does - but among all proposed solutions this is the most sound to me, kudos! – Romeo Kienzler Nov 07 '18 at 11:52
1

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.

mahesh
  • 1,028
  • 10
  • 24
0

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]
zipa
  • 27,316
  • 6
  • 40
  • 58