Use for loop or functools reduce() or numpy prod() or math prod() to find a product of list in Python. There are more ways to do it.
Get product of list in Python
Simple example code multiplies all values in a list in Python.
Use a for loop
Iterate over the list and multiply each element.
a_list = [2, 3, 4, 5] product = 1 for item in a_list: product = product * item print(product)
import functools to use reduce() function.
import functools import operator a_list = [2, 3, 4, 5] product = functools.reduce(operator.mul, a_list) print(product)
It returns an integer or a float value depending on the multiplication result.
import numpy a_list = [2, 3, 4, 5] product = numpy.prod(a_list) print(product)
A prod function has been included in the math module in the standard library,
import math a_list = [2, 3, 4, 5] product = math.prod(a_list) print(product)
Do comment if you have any doubts or suggestions on this Python product 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.