user5676791
user5676791

Reputation:

Individual list addition in python

If I have these lists:

a = [1,2,3]
b = [4,5,6]

how do I add each individual element in the list a by all in list b?

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

I have tried using 2 for loops but as an amateur, I imagine there is a more effective way. Cheers!

Upvotes: 2

Views: 199

Answers (4)

Vanojx1
Vanojx1

Reputation: 5574

What about handling n lists?

from itertools import product

def listSum(lists):
  return [sum(list) for list in product(*lists)]

print(listSum(([1,2,3],[4,5,6]))) #=> [5, 6, 7, 6, 7, 8, 7, 8, 9]
print(listSum(([1,2,3], ))) #=> [1, 2, 3]
print(listSum(([1,2,3],[4,5,6],[7,8,9]))) #=> [12, 13, 14, 13, 14, 15, 14, 15, 16, 13, 14, 15, 14, 15, 16, 15, 16, 17, 14, 15, 16, 15, 16, 17, 16, 17, 18]

Upvotes: 0

BoilingFire
BoilingFire

Reputation: 309

Simply

a = [1,2,3]
b = [4,5,6]
# Multiplication
final_list = [x*y for x in a for y in b]

[4, 5, 6, 8, 10, 12, 12, 15, 18]

# Addition
final_list = [x+y for x in a for y in b]

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

Upvotes: 4

Eric Duminil
Eric Duminil

Reputation: 54223

You can use itertools.product to calculate the cartesian product of a and b, and then calculate the product/sum of each pair:

>>> import itertools
>>> a = [1,2,3];b = [4,5,6]
>>> list(itertools.product(a,b)) # This step isn't needed. It's just to show the result of itertools.product
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
>>> [i + j for i, j in itertools.product(a, b)]
[5, 6, 7, 6, 7, 8, 7, 8, 9]
>>> [i * j for i, j in itertools.product(a, b)]
[4, 5, 6, 8, 10, 12, 12, 15, 18]

Upvotes: 3

zaidfazil
zaidfazil

Reputation: 9235

You could do addition also similarly as the previous answers,

>>> [i+j for i in a for j in b]
[5, 6, 7, 6, 7, 8, 7, 8, 9]

Upvotes: 4

Related Questions