Python Forum

Full Version: multiplying elements in a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How do I multiply elements in a list with each other?

ex:
If I have to lists
[4, 0.8, 23]
[0.3, 2, 3]
How do I make these lists become a new list which should be [1.2, 1.6, 69]
Hello,

you can try this:

a = [4, 0.8, 23]
b = [0.3, 2, 3]
c = list(map(lambda x: x[0] * x[1], zip(a, b)))
print(c)
Best Regards,

Nicolas TATARENKO
Hi @Olavv
You can do this using numpy

Here is answer:
import numpy as np

input1 = np.array([4, 0.8, 23])
input2 = np.array([0.3, 2, 3])

result = input1*input2
print(result)
Itertools & operator:
from itertools import starmap
from operator import mul

a = [4, 0.8, 23]
b = [0.3, 2, 3]

c = list(starmap(mul, zip(a, b)))
List comprehension:
a = [4, 0.8, 23]
b = [0.3, 2, 3]
c = [x * y for x, y in zip(a, b)]
With a for-loop and a list:
a = [4, 0.8, 23]
b = [0.3, 2, 3]

c = []
for x, y in zip(a, b):
    result = x * y
    c.append(result)
With a generator
from functools import reduce
from operator import mul


def mul_seq(*sequences):
    iterator = zip(*sequences)
    for multiplicators in iterator:
        yield reduce(mul, multiplicators)


a = [4, 0.8, 23]
b = [0.3, 2, 3]

c = list(mul_seq(a, b))

# or with more than two
d = list(mul_seq(a, b, c))
If you have big arrays, you should better use numpy, because this is optimized for matrix operation like broadcasting or matrix multiplication.