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

from math import prod				 # Importing prod function from Python's Math Module
a_list = [18, 74, 27, 192, 63]       # Define list whose elements to be multiplied

multiply_result = prod(a_list)       # Mutiplying Elements inside list together
	
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 🥳 🥳

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts