Open In App

Python | Multiply all numbers in the list

Last Updated : 07 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a list, print the value obtained after multiplying all numbers in a Python list. 

Examples: 

Input :  list1 = [1, 2, 3]
Output : 6
Explanation: 1*2*3=6

Input : list1 = [3, 2, 4]
Output : 24 

Multiply all Numbers in the List in Python

There are multiple approaches to performing multiplication within a list. In this context, we will utilize commonly employed methods on how to multiply in Python, as outlined below.

Multiply all numbers in the list using Traversal

Initialize the value of the product to 1(not 0 as 0 multiplied with anything returns zero). Traverse till the end of the list, multiply every number with the product. The value stored in the product at the end will give you your final answer.

Example:  In this example the below code uses a traversal approach in the function `multiplyList` to calculate the product of elements in lists `[1, 2, 3]` and `[3, 2, 4]`, resulting in outputs of 6 and 24, respectively.

Python




# Python program to multiply all values in the
# list using traversal
 
 
def multiplyList(myList):
 
    # Multiply elements one by one
    result = 1
    for x in myList:
        result = result * x
    return result
 
 
# Driver code
list1 = [1, 2, 3]
list2 = [3, 2, 4]
print(multiplyList(list1))
print(multiplyList(list2))


Output :

6
24

Time complexity: O(n), where n is the number of elements in the list.
Auxiliary space: O(1),

Multiply all numbers in the list using numpy.prod()

We can use numpy.prod() from import numpy to get the multiplication of all the numbers in the list. It returns an integer or a float value depending on the multiplication result.

Example :  In this example the below code uses `numpy.prod()` to find the product of elements in lists `[1, 2, 3]` and `[3, 2, 4]`, resulting in outputs of 6 and 24, respectively.

Python3




# Python3 program to multiply all values in the
# list using numpy.prod()
 
import numpy
list1 = [1, 2, 3]
list2 = [3, 2, 4]
 
# using numpy.prod() to get the multiplications
result1 = numpy.prod(list1)
result2 = numpy.prod(list2)
print(result1)
print(result2)


Output :

6 
24 

Time complexity: O(n), where n is the length of the input lists. 
Auxiliary space: O(1). 

Multiply all numbers in the list using lambda function

Lambda’s definition does not include a “return” statement, it always contains an expression that is returned. We can also put a lambda definition anywhere a function is expected, and we don’t have to assign it to a variable at all. This is the simplicity of lambda functions. The reduce() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new reduced result is returned. This performs a repetitive operation over the pairs of the list.

Example :  In this example the below code uses Python’s `functools.reduce` with a lambda function to multiply all values in lists `[1, 2, 3]` and `[3, 2, 4]`. The results, 6 and 24, are printed.

Python3




# Python3 program to multiply all values in the
# list using lambda function and reduce()
from functools import reduce
list1 = [1, 2, 3]
list2 = [3, 2, 4]
 
result1 = reduce((lambda x, y: x * y), list1)
result2 = reduce((lambda x, y: x * y), list2)
print(result1)
print(result2)


Output :

6
24

Time complexity: O(n) – where n is the length of the longer list.
Auxiliary space: O(1) – the memory used is constant, as no extra data structures are create.

Multiply all numbers in the list using prod function of math library

Starting Python 3.8, a prod function has been included in the math module in the standard library, thus no need to install external libraries.

Example :In this example the below code utilizes Python’s `math.prod` function to calculate the product of all values in lists `[1, 2, 3]` and `[3, 2, 4]`. The results, 6 and 24, are printed.

Python3




# Python3 program to multiply all values in the
# list using math.prod
import math
list1 = [1, 2, 3]
list2 = [3, 2, 4]
 
result1 = math.prod(list1)
result2 = math.prod(list2)
print(result1)
print(result2)


Output:

6
24

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(1)

Multiply all numbers in the list using mul() function of operator module. 

First we have to import the operator module then using the mul() function of operator module multiplying the all values in the list. In this example the below code multiplies all numbers in the list `[1, 2, 3]` using the `operator` module’s `mul` function. It iterates through the list, updating the result variable, and prints the final product (output: 6).

Python3




# Python 3 program to multiply all numbers in
# the given list by importing operator module
 
from operator import*
list1 = [1, 2, 3]
m = 1
for i in list1:
  # multiplying all elements in the given list
  # using mul function of operator module
    m = mul(i, m)
# printing the result
print(m)


Output :

6

Time complexity: O(n), where n is the length of the input list. Auxiliary space: O(1), which is constant.

Multiply all numbers in the list using For Loop

To multiply all numbers in a list using a For Loop, you can iterate through each element of the list and update a running product variable.

Example :In this example, the multiply_list function takes a list as input and initializes a variable product to 1. It then iterates through each element in the list, updating the product by multiplying it with the current element

Python3




def multiply_list(list1):
    # Initialize product to 1
    product = 1
     
    # Iterate through each element in the list
    for element in list1:
        product *= element
     
    return product
 
# Example
list1 = [1, 2, 3, 4, 5]
result = multiply_list(list1)
print(result)


Output :

120 

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(1).

Multiply all numbers in the list using traversal by index

In this example the below code defines a function, `multiplyList`, to find the product of list elements using a traversal approach. It sequentially multiplies each element in the list. Demonstrations with lists `[1, 2, 3]` and `[3, 2, 4]` yield outputs of 6 and 24, respectively.

Python3




# Python program to multiply all values in the
# list using traversal
 
def multiplyList(myList) :
     
    # Multiply elements one by one
    result = 1
    for i in range(0,len(myList)):
        result = result * myList[i]
    return result
     
# Driver code
list1 = [1, 2, 3]
list2 = [3, 2, 4]
print(multiplyList(list1))
print(multiplyList(list2))


Output :

6 
24 

Time complexity: O(n), where n is the length of the input list.  Auxiliary space: O(1).

Multiply all numbers in the list using itertools.accumulate

The `itertools.accumulate` function is used for cumulative operations on an iterable. In this case, it accumulates the product of elements in the lists. The lambda function `(lambda x, y: x * y)` defines the multiplication operation, and the final results are obtained from the accumulated values.

Example : In this example the below code utilizes `itertools.accumulate` with a lambda function to multiply values in lists `[1, 2, 3]` and `[3, 2, 4]`. Accumulated results are converted to lists, and the last elements are printed (outputs: 6 and 24).

Python




# Python3 program to multiply all values in the
# list using lambda function and accumulate()
from itertools import accumulate
list1 = [1, 2, 3]
list2 = [3, 2, 4]
 
result1 = list(accumulate(list1, (lambda x, y: x * y)))
result2 = list(accumulate(list2, (lambda x, y: x * y)))
print(result1[-1])
print(result2[-1])


Output:

6
24

Time complexity : O(n), where n is the length of the input list. Auxiliary space : O(n) 

Multiply all numbers in the list using the recursive function 

The function product_recursive() takes a list of numbers as input and returns the product of all the numbers in the list, using a recursive approach.

Example : In this example the below code defines a recursive function, `product_recursive`, to calculate the product of a list’s elements. It handles base and recursive cases, demonstrating its functionality with lists `[1, 2, 3]` and `[3, 2, 4]`, resulting in outputs of 6 and 24, respectively.

Python3




def product_recursive(numbers):
    # base case: list is empty
    if not numbers:
        return 1
    # recursive case: multiply first element by product of the rest of the list
    return numbers[0] * product_recursive(numbers[1:])
list1 = [1, 2, 3]
product = product_recursive(list1)
print(product)  # Output: 6
 
list2 = [3, 2, 4]
product = product_recursive(list2)
print(product)  # Output: 24


Output :

6
24

Time complexity : O(n), where n is the number of elements in the list.
Space complexity :O(n)

Multiply all numbers in the list Using reduce() and the mul() function

One approach to solve this problem is to use the built-in 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.

Example : In this example the below code utilizes `functools.reduce` and `operator.mul` to multiply elements in the list [1, 2, 3], printing the cumulative product (output: 6). It showcases the effectiveness of the `reduce` function for concise cumulative operations.

Python3




from functools import reduce
from operator import mul
 
list1 = [1, 2, 3]
result = reduce(mul, list1)
 
print(result)


Output :

6

Time complexity: O(n)
Auxiliary space: O(1)



Similar Reads

Python | Multiply Integer in Mixed List of string and numbers
Sometimes, while working with Python, we can come across a problem in which we require to find the product of list. This problem is easier to solve. But this can get complex in case we have a mixture of data types to go along with it. Let’s discuss certain ways in which this task can be performed. Method #1: Using Type casting + Exception Handling
7 min read
Python - Multiply all cross list element pairs
Sometimes, while working with Python lists, we can have a problem in which we need to perform the multiplication of each element of list with another list. This can have applications in both web development and day-day programming. Let's discuss certain ways in which this task can be performed. Method #1: Using list comprehension This is the most s
8 min read
Multiply matrices of complex numbers using NumPy in Python
In this article, we will discuss how to multiply two matrices containing complex numbers using NumPy but first, let's know what is a complex number. A Complex Number is any number that can be represented in the form of x+yj where x is the real part and y is the imaginary part. Multiplication of two complex numbers can be done using the below formul
2 min read
Python Program to Multiply Two Binary Numbers
Given two binary numbers, and the task is to write a Python program to multiply both numbers. Example: firstnumber = 110 secondnumber = 10 Multiplication Result = 1100 We can multiply two binary numbers in two ways using python, and these are: Using bin() functions andWithout using pre-defined functionsMethod 1: Using bin Functions Now, Let's write
2 min read
Python - How to Multiply all items in Tuple
Sometimes, while programming, we have a problem in which we might need to perform product among tuple elements. This is an essential utility as we come across product operation many times and tuples are immutable and hence required to be dealt with. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list() + loop The
6 min read
Python program to multiply all the items in a dictionary
Python program to illustrate multiplying all the items in a dictionary could be done by creating a dictionary that will store all the key-value pairs, multiplying the value of all the keys, and storing it in a variable. Example: Input: dict = {'value1':5, 'value2':4, 'value3':3, 'value4':2, 'value5':1} Output: ans = 120 Input: dict = {'v1':10, 'v2'
2 min read
Python | Repeat and Multiply list extension
Sometimes, while working with Python list, we can have a problem in which we need to extend a list in a very customized way. We may have to repeat contents of list and while doing that, each time new list must be a multiple of original list. This incremental expansion has applications in many domains. Let's discuss a way in which this task can be p
6 min read
Python - Multiply two list
There can be many situations in which one requires to find index wise product of two different lists. This can have a possible applications in day-day programming. Lets discuss various ways in which this task can be performed. Method #1 : Naive Method In this method, we simply run a loop and append to the new list the product of the both list eleme
7 min read
Python - Multiply Consecutive elements in list
While working with python, we usually come by many problems that we need to solve in day-day and in development. Specially in development, small tasks of python are desired to be performed in just one line. We discuss some ways to compute a list consisting of elements that are successive product in the list. Method #1 : Using list comprehension Nai
7 min read
Python program to multiply two matrices
Given two matrix the task is that we will have to create a program to multiply two matrices in python. Examples: Input : X = [[1, 7, 3], [3, 5, 6], [6, 8, 9]] Y = [[1, 1, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]] Output : [55, 65, 49, 5] [57, 68, 72, 12] [90, 107, 111, 21]Recommended: Please try your approach on {IDE} first, before moving on to the soluti
4 min read
Practice Tags :
three90RightbarBannerImg