Published on

Multiplying elements in a Python list

Authors
  • avatar
    Name
    hwahyeon
    Twitter

In Python, the sum() function allows you to add all the elements in a list. But what if you want to multiply them instead?

Starting with Python 3.8, you can use the prod() function from the math module.

import math

numbers = [1, 2, 3, 4, 5]
print(math.prod(numbers))  # 120

However, if you're using a version of Python before 3.8, you'll need to write your own function to multiply all the elements.

def custom_prod(iterable):
    # The identity element for multiplication is 1
    result = 1
    for num in iterable:
        result *= num
    return result

numbers = [1, 2, 3, 4, 5]
print(custom_prod(numbers))  # 120