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
2
  • 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 minimal reproducible example? Commented Nov 7, 2018 at 10:53
  • Possible duplicate of Matrix Multiplication in python? Commented Nov 7, 2018 at 10:54

3 Answers 3

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

1 Comment

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!
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.

1 Comment

that's the solution I even prefer over mine :) Especially since it doesn't need external imports
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.