Home > Backend Development > Python Tutorial > How to calculate the product of all numbers in a list in Python? (code example)

How to calculate the product of all numbers in a list in Python? (code example)

青灯夜游
Release: 2019-03-21 10:51:38
Original
48115 people have browsed it

How to multiply all numbers in a list in Python and then return the product value. The following article will introduce to you three methods of multiplying all the numbers in the list and calculating the product value. I hope it will be helpful to you.

How to calculate the product of all numbers in a list in Python? (code example)

Method 1: Use traversal

to initialize the value of the variable product to 1 (not 0 Multiplying any value by 0 returns zero). Traverse to the end of the list and multiply each number by the variable product. The final value stored in the variable product is the product of all the numbers in the list.

Code example:

def multiplyList(myList) : 
    # 将列表元素一 一相乘
    product = 1
    for x in myList: 
         product = product * x  
    return product  
list1 = [1, 2, 3]  
list2 = [3, 2, 4] 
print(multiplyList(list1)) 
print(multiplyList(list2))
Copy after login

Output:

6
24
Copy after login
Copy after login

Method 2: Use numpy.prod()

We can use the numpy.prod() method of the numpy module to calculate the product of all the numbers in the list; it will return an integer or floating point value depending on the result of the multiplication.

Code example:

import numpy  
list1 = [2, 3, 4]  
list2 = [4, 6, 4] 
  
# 使用numpy.prod()
result1 = numpy.prod(list1) 
result2 = numpy.prod(list2) 
print(result1) 
print(result2)
Copy after login

Output:

24
96
Copy after login

Method 3: Use lambda reduce() function

Code example:

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)
Copy after login

Output:

6
24
Copy after login
Copy after login

Related video tutorial recommendation: "Python Tutorial"

The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to calculate the product of all numbers in a list in Python? (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template