Python | Multiplying All Numbers in a List

Elements of a List can be multiplied with each other using two ways => Traversal and math.prod function. Let’s discuss each one of these ways.

Multiplying Elements in a List using Traversal

  • Define a function multiplylistelements(a_list) which accept list as a parameter
  • Initialise a variable result equals to 1
  • Loop over elements in list using for loop each time multiplying element to result variable
  • Return result variable just outside for loop

Let’s put together all of these steps as Python Code for Multiplying Elements in a List.

# Python program to multiply all values in the list using traversal

a_list = [18, 74, 27, 192, 63]       # Define list whose elements to be multiplied

def multiplylistelements(a_list) :
	# Multiply elements one by one
	result = 1
	for x in a_list :
		result = result * x
	return result
	
print("Final result of multiplication of List elements is => ", multiplylistelements(a_list))

Output of Above Code

Final result of multiplication of List elements is =>  435020544

Multiplying Elements in a List using math.prod Function

From Python’s version 3.8 to onwards prod(iterable, *, start = 1) function was newly defined in Python’s math Module. This prod function just takes values inside an iterable and multiply these until it reaches to end value inside iterable, do not that if values inside iterable are non-numeric then this function will show error(Like TypeError).

# Python program to multiply all values in the list using math.prod function

# Importing prod function from Python's Math Module
from math import prod

# Define list whose elements to be multiplied
a_list = [18, 74, 27, 192, 63]     

# Mutiplying Elements inside list together
multiply_result = prod(a_list)       
	
print("Final result of multiplication of List elements is => ", multiply_result)

Output of Above Code

Final result of multiplication of List elements is =>  435020544

I hope that this article helped using to understand How to multiply elements of a list with each other? Moreover if in case you know any other possible approach for doing this, then let me know in comments. I’ll update this article accordingly.
Happy Coding 🥳 🥳

Comments to: Python | Multiplying All Numbers in a List

Your email address will not be published.