Skip to content

Python product of list | Example code

  • by

Use for loop or functools reduce() and numpy prod() or math prod() to find a product of a list in Python. There are more ways to do it.

To find the product of all elements in a list in Python, you can use a loop to iterate through the elements and multiply them together. Here’s a simple example:

def product_of_list(lst):
    result = 1
    for num in lst:
        result *= num
    return result

# Example usage:
my_list = [2, 3, 4, 5]
result = product_of_list(my_list)
print(result)

In this example, the product_of_list function takes a list (lst) as an argument and initializes a variable result to 1. It then iterates through each element in the list, multiplying it with the current value of result. The final result is the product of all the elements in the list.

Get the product of the list in Python

A 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.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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading