A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python-multiply-numbers-list-3-different-ways/ below:

Multiply All Numbers in the List in Python

Multiply All Numbers in the List in Python

Last Updated : 03 May, 2025

Our task is Multiplying all numbers in a list Using Python. This can be useful in calculations, data analysis, and whenever we need a cumulative product. In this article we are going to explore various method to do this.

Using a loop

We can simply use a loop (for loop) to iterate over the list elements and multiply them one by one.

Python
a = [2, 4, 8, 3]
res = 1

for val in a:
	res = res * val
    
print(res)

Explanation: We start with res = 1 and then multiply each number in the list with res using a for loop.

Using math.prod()

The math library in Python provides the prod() function to calculate the product of each element in an iterable.

Note: The prod() method was added to the math library in Python 3.8. So, it only available with Python 3.8 or greater versions.

Python
import math

a = [2, 4, 8, 3]
res = math.prod(a)  

print(res)

Explanation:

Using reduce() and mul()

We can use reduce() function from the functools module, which can apply a function to an iterable in a cumulative way. We can use the operator.mul() function to multiply the elements together.

Python
from functools import reduce
from operator import mul

a = [2, 4, 8, 3]
res = reduce(mul, a)

print(res)

Explanation:

Related Article:


Python program to multiply all numbers in the list


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4