Multiply All Elements of a List in Python

  • Post category:List

Multiplying all elements of a list in Python can be done using a loop or the reduce() function from the functools module. Here are two examples:

Example 1:

numbers = [1, 2, 3, 4, 5]
product = 1
for number in numbers:
    product *= number
print(f"The product of all elements is: {product}")

Output:

The product of all elements is: 120

Example 2:

from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(f"The product of all elements is: {product}")

Output:

The product of all elements is: 120