Editor

Python Program to Multiply All Numbers in a List

Beginner · Lists

This program finds the product of a list, which is the result of multiplying all its numbers together. For [2, 3, 4, 5] the product is 2 x 3 x 4 x 5 = 120. It keeps a running product, just as a sum keeps a running total.

Program

multiply_list_elements.py
numbers = [2, 3, 4, 5] # or: numbers = [int(x) for x in input("Enter numbers: ").split()]
product = 1 # start at 1, not 0: anything times 0 is 0
for num in numbers:
product *= num # same as product = product * num
print("List:", numbers)
print("Product of all numbers:", product)
Output
List: [2, 3, 4, 5]
Product of all numbers: 120

How it works

  1. product starts at 1, because multiplying by 1 leaves a number unchanged. Starting at 0 would make every answer 0.
  2. The loop multiplies product by each number in turn: 1 x 2 = 2, then 2 x 3 = 6, then 6 x 4 = 24, then 24 x 5 = 120.
  3. If the list contains a 0, the product is 0.
  4. For an empty list the loop never runs, so the product stays 1, which mathematicians call the empty product.

Other ways to write it

Using math.prod()

Using math.prod()
import math
numbers = [2, 3, 4, 5]
print("Product of all numbers:", math.prod(numbers))
print("Product of an empty list:", math.prod([]))
print("Product of decimals:", math.prod([1.5, 2, 4]))
Output
Product of all numbers: 120
Product of an empty list: 1
Product of decimals: 12.0

math.prod() (Python 3.8 or newer) multiplies everything in a list or tuple in one call.

Using functools.reduce()

Using functools.reduce()
from functools import reduce
numbers = [2, 3, 4, 5]
product = reduce(lambda a, b: a * b, numbers)
print("Product of all numbers:", product)
Output
Product of all numbers: 120

reduce() combines the first two numbers, then combines that result with the next number, and so on until one value is left.

Try it yourself

Change the program to multiply only the odd numbers in the list.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises