![]() |
VOOZH | about |
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.
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.
192
Explanation:
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.
192
Explanation:
We can simply use a loop (for loop) to iterate over the list elements and multiply them one by one.
192
Explanation: start with res = 1 and then multiply each number in the list with res using a for loop.