Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply elements of inner lists as a list comprehension

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.

like image 615
amit.shipra Avatar asked Mar 27 '15 17:03

amit.shipra


People also ask

How do you multiply list comprehension in Python?

Multiply two lists using for loop For this purpose, we can use Zip Function. The zip() function in python can combine the contents of 2 or more iterables. Zip Function returns a zipped output. We can then simply store the output in Result and Display it on the console.

How do you multiply lists with different lists?

Use zip() to multiply two lists Pass both lists into zip(*iterables) to get a list of tuples that pair elements with the same position from both lists. Use a for loop to multiply these elements together and append them to a new list. Use a list comprehension for a more compact implementation.

Can you do nested list comprehension?

As it turns out, you can nest list comprehensions within another list comprehension to further reduce your code and make it easier to read still. As a matter of fact, there's no limit to the number of comprehensions you can nest within each other, which makes it possible to write very complex code in a single line.


3 Answers

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?

like image 172
Martijn Pieters Avatar answered Oct 12 '22 12:10

Martijn Pieters


Another approach using numpy

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

Ref - Documentation on prod

like image 35
Bhargav Rao Avatar answered Oct 12 '22 10:10

Bhargav Rao


Try:

products = [reduce(lambda x, y: x * y, l) for l in lst]
like image 1
Guillaume Lemaître Avatar answered Oct 12 '22 10:10

Guillaume Lemaître