Reputation: 197
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.
Upvotes: 5
Views: 7623
Reputation: 52071
Another approach using numpy
>>> from numpy import prod
>>> [prod(x) for x in lst]
[6, 24, 30, 9]
Ref - Documentation on prod
Upvotes: 3
Reputation: 61666
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)
Upvotes: 0
Reputation: 1121644
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?
Upvotes: 9
Reputation: 6389
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]
Upvotes: 1
Reputation: 13869
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
.
Upvotes: 1
Reputation: 1280
Try:
products = [reduce(lambda x, y: x * y, l) for l in lst]
Upvotes: 1