1

I wonder how can I multiply each element in two different lists.

For example :

list_a = [1,2,3,4,5] list_b = [10,20,30,40,50]

I want to make it 1X10 2X20 3X30 4X40 5X50

so that the result will be 10, 40, 90, 160, 250

I would really appreciate if you can help me.

Shivkumar kondi
  • 6,458
  • 9
  • 31
  • 58
adchoi_97
  • 21
  • 1
  • 2
    Possible duplicate of [How do I multiply each element in a list by a number?](https://stackoverflow.com/questions/35166633/how-do-i-multiply-each-element-in-a-list-by-a-number) – Nick Brady Aug 04 '17 at 05:24
  • `zip` in best method for this.[zip](https://docs.python.org/3.3/library/functions.html#zip) – Rohit-Pandey Aug 04 '17 at 22:10

5 Answers5

3

You can use zip function as below.

>>> list_a = [1,2,3,4,5]
>>> list_b = [10,20,30,40,50]
>>> [(x[0]*x[1]) for x in zip(list_a,list_b)]
[10, 40, 90, 160, 250]
voidpro
  • 1,652
  • 13
  • 27
1

Using zip():

list_a = [1,2,3,4,5]
list_b = [10,20,30,40,50]
final = [k*v for k, v in zip(list_a, list_b)]
print final

Output:

[10, 40, 90, 160, 250]
Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43
  • For Python 3 you need to put `k,v` in parenthesis like this : `(k,v)`. Final line is `final = [k*v for (k, v) in zip(list_a, list_b)]`. – Zcode Aug 04 '17 at 11:44
  • 1
    Sorry, you're right. Python 3 documentation said that parenthesis were needed but it's only the return part of the comprehension list. – Zcode Aug 04 '17 at 11:56
0
a = [1,2,3,4,5] 
b = [10,20,30,40,50]
print [a[i]*b[i] for i in range(len(b))]

This will helpful for you

Badri Gs
  • 320
  • 2
  • 11
0
a = [1,2,3,4,5]
b = [i*i*10 for i in a]
Devaraj Phukan
  • 196
  • 1
  • 9
-1

A cleaner version would be :

a,b = [1,2,3,4,5],[10,20,30,40,50]
for i,j in zip(a,b):
    print '%d x %d = '%(i,j),'%d units'% ((i*j))
Ubdus Samad
  • 1,218
  • 1
  • 15
  • 27