Multiply All Elements in list of Python

Multiply All Elements in list of Python

In this tutorial, we will learn how we can multiply all the elements of a list in Python.

Let us have a look at some examples to understand our objective-

We can observe that in the output we have obtained the product of all the elements present in the list.

Since the first element is three, a is printed three times in the output.

We will learn the following methods-

  1. Traversing the list
  2. Using NumPy
  3. Using lambda

Let’s start with the first one,

Traversing the list

Consider the program given below-

Output:

The multiplication of all the elements of list_value1 is: 240240
The multiplication of all the elements of list_value2 is: 5040

Explanation-

It’s time to have a look at the explanation of the above program-

  1. In the first step, we have created a function that will make the list as an input.
  2. In the function definition, we have used a for loop that takes each element from the list, multiplies it with one initially, and then prints the resultant value of the product.
  3. In the next step, we have initialized the lists and then passed them into our function.
  4. On executing this program, the desired output is displayed.

In the second program, we will see how NumPy can help us to implement the same.

Using NumPy

The following program illustrates how it can be done in Python.

Output:

The multiplication of all the elements of list_value1 is: 240240
The multiplication of all the elements of list_value2 is: 5040

Explanation-

Let’s understand what we have done in the above program.

  1. In the first step, we have imported the NumPy module.
  2. In the next step, we have initialized the values of the two lists, list_value1 and list_value2.
  3. After this, we will use prod() that will compute the product of the elements present in the lists.
  4. On executing the program, the expected output is displayed.

Finally, we will learn how lambda can be used to multiply the elements of our list.

Using lambda

The program given below demonstrates the same-

Output:

The multiplication of all the elements of list_value1 is: 240240
The multiplication of all the elements of list_value2 is: 5040

Explanation-

Let us understand what happened in the above program.

  1. In the first step, we have imported reduce from
  2. After this, we have initialized the two lists, list_value1 and list_value2.
  3. We have used the precise way of defining functions, which is lambda, and then provided the required functionality.
  4. On executing the program, the desired values are displayed.

Conclusion

In this tutorial, we learned the various approaches of multiplying the elements present in the list in Python.


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263363.html

(0)
上一篇 2022年5月30日
下一篇 2022年5月30日

相关推荐

发表回复

登录后才能评论