Python Practice › List Programs › Program 4
Product of all elements
Write a Python program to find the product of all elements in a list.
Input
[2, 3, 4, 5]
Output
120 120
Approach
- Start at 1 and multiply, or use
math.prod().
Solution
import math numbers = [2, 3, 4, 5]product = 1for n in numbers: product *= nprint(product, math.prod(numbers))Output
120 120
Line by line
Line 4
Starting at 1 (not 0) keeps the product correct.
Learn the concept
New to this topic? Read the lesson, then come back.
1 thought on “Product of all elements”