You can use reduce()
to apply multiplication to a list of integers, together with operator.mul()
to do the actual multiplication:
from functools import reduce
from operator import mul
products = [reduce(mul, l) for l in lst]
In Python 3, reduce()
has been moved to functools.reduce()
, hence the supporting import
statement. As functools.reduce
exists since Python 2.6, it is simply easier to import it from there if you need to keep your code compatible with both Python 2 and 3.
Demo:
>>> from operator import mul
>>> lst = [[1, 2, 3], [1, 2, 3, 4], [5, 6], [9]]
>>> [reduce(mul, l) for l in lst]
[6, 24, 30, 9]
operator.mul()
can be replaced with lambda x, y: x * y
but why have a dog and bark yourself?