5

Could this be done in single line using list comprehension?

lst = [[1, 2, 3], [1, 2, 3, 4], [5, 6], [9]]
products = ?? (Multiple each list elements)

Desired output = [6, 24, 30, 9]

I tried something like:

products = [l[i] * l[i + 1] for l in lst for i in range(len(l) - 1)]

but didn't work.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
amit.shipra
  • 167
  • 2
  • 16

6 Answers6

9

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

Another approach using numpy

>>> from numpy import prod
>>> [prod(x) for x in lst] 
[6, 24, 30, 9]

Ref - Documentation on prod

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
1

Try:

products = [reduce(lambda x, y: x * y, l) for l in lst]
Guillaume Lemaître
  • 1,230
  • 13
  • 18
1

Yes, you can use reduce and a lambda expression within a list comprehension:

>>> [reduce(lambda x, y: x * y, innerlst) for innerlst in lst]
[6, 24, 30, 9]

Note, in Python 3, reduce was moved to the functools module so you must import from it there:

from functools import reduce

If you don't want to use the lambda expression, it can be replaced entirely by operator.mul.

Shashank
  • 13,713
  • 5
  • 37
  • 63
1

Using this solution for making a product operator for lists you can do something like:

    lst = [[1, 2, 3], [1, 2, 3, 4], [5, 6], [9]]
    import operator
    from functools import reduce # Valid in Python 2.6+, required in Python 3
    def prod(numeric_list):
        return reduce(operator.mul, numeric_list, 1)

    [prod(l) for l in lst]

Ouput:

    Out[1]: [6, 24, 30, 9]
Community
  • 1
  • 1
Scott
  • 6,089
  • 4
  • 34
  • 51
0

Starting Python 3.8, and the addition of the prod function to the math module:

import math

# lst = [[1, 2, 3], [1, 2, 3, 4], [5, 6], [9], []]
[math.prod(l) for l in lst]
# [6, 24, 30, 9, 1]

Note that empty sub-lists will get a product value of 1, which is defined by the value of start:

math.prod(iterable, *, start=1)

Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190