Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Individual list addition in python

Tags:

python

list

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!


1 Answers

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]

like image 131
BoilingFire Avatar answered Jan 02 '26 23:01

BoilingFire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!