The Python math module has math.prod() function, by using it you can write a Python function to multiply all the numbers in a list. Or you can use loop logic for the same.
Note: math.prod
is a new function (from Python 3.8).
Python function to multiply all the numbers in a list
Simple example code Multiply all numbers in the list.
Using math.prod
import math
list1 = [1, 2, 3]
res = math.prod(list1)
print("Multiplication of List: ", res)
Output:
Using for loop in user define a function
Python functions have to code to traverse the list and multiply each element.
def multiply(numbers):
total = 1
for x in numbers:
total *= x
return total
Lst = [8, 2, 3, -1, 7]
print(multiply(Lst))
Output: -336
Use functools.reduce() to multiply all values in a list
import functools
import operator
a_list = [2, 3, 4]
product = functools.reduce(operator.mul, a_list)
print(product)
Output: 24
Do comment if you have any doubts or suggestions on this Python multiplication code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.