DEV Community

Cover image for Python 3 ways to compute multiplication of list & how to to reduce in general
jzfrank
jzfrank

Posted on

Python 3 ways to compute multiplication of list & how to to reduce in general

How to compute the multiplication of a list in python?

a = [1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

for loop

The most intuitive and easy solution.

res = 1
for i in a:
    res *= i
Enter fullscreen mode Exit fullscreen mode

math.prod or np.prod

math or numpy module has an embedded function for multiplication of list.

import math
res = math.prod(a)
Enter fullscreen mode Exit fullscreen mode

or

import numpy as np
res = np.prod(a)
Enter fullscreen mode Exit fullscreen mode

functools.reduce

This is personally my favourite, it is an elegant one-liner with easy extensions to compute other tasks related to "reduce a list to a single number".

import functools
res = functools.reduce(lambda x, y: x * y, a)
Enter fullscreen mode Exit fullscreen mode

say if you want to piece together a list of strings

functools.reduce(lambda x,y: x+y, ["hi,", " world"])
Enter fullscreen mode Exit fullscreen mode

say if you want to add a list of nums:

functools.reduce(lambda x,y: x+y, [1, 2, 3, 4])
Enter fullscreen mode Exit fullscreen mode

Top comments (0)