Javaexercise.com

Python Program To Get Product Of List Elements

In this article, we will learn how we can multiply all the numbers in the list. In Python, we can do this task in several ways.

  1. Using loop

  2. Using numpy.prod() function

  3. Using reduce() function

  4. Using math.prod() function

Python Program to Multiply all the numbers of List using loop

In this approach, we used a variable to store the product. This variable is initialized to 1. We loop through the list and multiply every number with the product. When the loop terminates, the product variable stores the final result. Look at the code below.

# Initialise a list
je_list = [ 1, 3, 43, 66, 321, 4 ]
​
# Instialise a variable to store the product
je_product = 1
​
# iterate through the list
for je_num in je_list:
    je_product = je_product*je_num
​
# Print the result
print(je_product)

Output:

10931976

We have initialized the product variable with 1 and not with 0 because anything multiplied by 0 will result in 0.

Multiply all the numbers of List Using numpy.prod() function

The NumPy library in python contains a function called prod(). This method takes a list as its argument and returns the product of all the elements in the list. It is a concise and single-line solution to get a product of the list. Look at the code below:

import numpy as np;

# Initialise a list
je_list = [ 1, 3, 43, 66, 321, 4 ]

# use to np.prod() to find the product
je_product = np.prod(je_list)

# Print the result
print(je_product)

Output:

10931976

Multiply all the numbers of List Using reduce() function

In this approach, we make use of the reduce function. This function takes two arguments, a function, and a list. The function is called with the list passed and a reduced result is produced.

Reduction means that the values of the list are combined to produce a single result. In this case, we pass a lambda function as the argument. Look at the code below.

from functools import reduce
​
# Initialise a list
je_list = [ 1, 3, 43, 66, 321, 4 ]
​
# Using reduce and lambda function to find the product
je_product = reduce((lambda x, y: x * y), je_list)
​
# Print the result
print(je_product)

Output:

10931976

Multiply all the numbers of List Using math.prod() function

In Python 3.8, the prod() function was included in the math library. This function takes a list and returns the product of the list. Look at the code below.

import math

# Initialise a list
je_list = [ 1, 3, 43, 66, 321, 4 ]

# Using reduce and lambda function to find the product
je_product = math.prod(je_list)

# Print the result
print(je_product)

Output:

10931976