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.
import math list1 = [1, 2, 3] res = math.prod(list1) print("Multiplication of List: ", res)
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))
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)
Do comment if you have any doubts or suggestions on this Python multiplication code.
Note: IDE: PyCharm 2021.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.