The Python [ Multiply all numbers in the list 4 different ways coding

Given a listing, print the worth obtained after multiplying all numbers in a listing.
Examples:

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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and study the fundamentals.

To start with, your interview preparations Enhance your Data Structures ideas with the Python DS Course. And to start along with your Machine Learning Journey, be a part of the Machine Learning – Basic Level Course

 

Method 1: Traversal

Initialize the worth of the product to 1(not 0 as 0 multiplied with something returns zero). Traverse until the tip of the listing, multiply each quantity with the product. The worth saved within the product on the finish gives you your ultimate reply.
Below is the Python implementation of the above method:

Python

Output:

6 24

Method 2: Using numpy.prod()

We can use numpy.prod() from import numpy to get the multiplication of all of the numbers within the listing. It returns an integer or a float worth relying on the multiplication result.
Below is the Python3 implementation of the above method:

Python3

Output:

6 24

 

Method 3 Using lambda perform: Using numpy.array

Lambda’s definition doesn’t include a “return” assertion, it all the time incorporates an expression that’s returned. We may also put a lambda definition wherever a perform is predicted, and we don’t need to assign it to a variable in any respect. This is the simplicity of lambda features. The scale back() perform in Python takes in a perform and a listing as an argument. The perform is known as with a lambda perform and a listing and a new lowered result is returned . This performs a repetitive operation over the pairs of the listing.
Below is the Python3 implementation of the above method:

Python3

Output:

6 24

Method 4 Using prod perform of math library: Using math.prod

Starting Python 3.8, a prod perform has been included within the math module in the usual library, thus no want to put in exterior libraries.
Below is the Python3 implementation of the above method:

Python3

Output:

6 24

 

Add a Comment

Your email address will not be published.