The equivalent of sum() for multiplication in Python

avatar

Borislav Hadzhiev

Last updated: Jul 4, 2022

banner

Photo from Unsplash

The equivalent of sum() for multiplication in Python #

The equivalent of sum() for multiplication is the math.prod() method. The math.prod method takes an iterable and calculates the product of all elements in the iterable.

main.py
import math my_list = [2, 2, 2] result = math.prod(my_list) print(result) # 👉️ 8

Make sure to import the math module.

The math.prod method calculates the product of all the elements in the provided iterable.

The method takes the following 2 arguments:

NameDescription
iterableAn iterable whose elements to calculate the product of
startThe start value for the product (defaults to 1)

If the iterable is empty, the start value is returned.

Note that the math.prod function is intended for use with numeric values.

If you have digits that are wrapped in strings, use the int() or float() classes to convert them to numbers first.

main.py
import math my_list = ['2', '2', '2'] result = math.prod(map(int, my_list)) print(result) # 👉️ 8

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

Each string in the list gets passed to the int() class and gets converted to an integer.

Alternatively, you can use the reduce() function to multiply the values in an iterable.

main.py
from functools import reduce from operator import mul my_list = [2, 2, 2] result = reduce(mul, my_list, 1) print(result) # 👉️ 8

The reduce function takes the following 3 parameters:

NameDescription
functionA function that takes 2 parameters - the accumulated value and a value from the iterable.
iterableEach element in the iterable will get passed as an argument to the function.
initializerAn optional initializer value that is placed before the items of the iterable in the calculation.
The reduce() function calls the provided reducer function (mul) with the accumulated value and an item from the iterable.

The mul function from the operator module is the same as a * b.

The result variable stores the multiplication result for the items in the iterable.

If the iterable is empty and the initializer argument is provided, the initializer is returned.

main.py
from functools import reduce from operator import mul my_list = [] result = reduce(mul, my_list, 1) # 👈️ initializer of 1 print(result) # 👉️ 1
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.