Multiply All Numbers in the List in Python
Given a list of numbers, the task is to find the product of all elements in the list. Multiplying all numbers in a list means multiplying each element together to get a single result.
For example:
For, arr = [2, 3, 4], result is 2 × 3 × 4 = 24.
arr = [1, 5, 7, 2], result is 1 × 5 × 7 × 2 = 70.
Let’s explore different methods to multiply all numbers in the list one by one.
Using math.prod()
The math library in Python provides the prod() function to calculate the product of each element in an iterable.
Note: prod() method was added to the math library in Python 3.8. So, it is only available with Python 3.8 or greater versions.
import math
a = [2, 4, 8, 3]
res = math.prod(a)
print(res)
Output
192
Explanation:
- a = [2, 4, 8, 3]: A list of integers.
- math.prod(a): Multiplies all elements in the list (2 * 4 * 8 * 3).
- print(res): Outputs the result of the multiplication (192).
Using reduce() and mul()
We can use reduce() function from the functools module, which can apply a function to an iterable in a cumulative way. We can use the operator.mul() function to multiply the elements together.
from functools import reduce
from operator import mul
a = [2, 4, 8, 3]
res = reduce(mul, a)
print(res)
Output
192
Explanation:
- a = [2, 4, 8, 3]: A list of integers.
- reduce(mul, a): Applies the mul operator (multiplication) cumulatively to the elements of a (i.e., 2 * 4 * 8 * 3).
- print(res): Outputs the result of the multiplication (192).
Using a loop
We can simply use a loop (for loop) to iterate over the list elements and multiply them one by one.
a = [2, 4, 8, 3]
res = 1
for val in a:
res = res * val
print(res)
Output
192
Explanation: start with res = 1 and then multiply each number in the list with res using a for loop.