Python product of list | Example code

  • by

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)

Output:

Python product of list

Use functools.reduce()

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)

Using numpy.prod()

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)

Using math.prod

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)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.