Is it possible to emulate something like sum() using list comprehension ?
For example - I need to calculate the product of all elements in a list :
list = [1, 2, 3] product = [magic_here for i in list] #product is expected to be 6
Code that is doing the same :
def product_of(input): result = 1 for i in input: result *= i return result
To do sum, you need to have a starting list with an identity of [0], starting with [1] works for product because you are multiplying the first number by 1, hence the change to [0].
sum() function in PythonSum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers.
No; a list comprehension produces a list that is just as long as its input. You will need one of Python's other functional tools (specifically reduce()
in this case) to fold the sequence into a single value.
>>> from functools import reduce >>> from operator import mul >>> nums = [1, 2, 3] >>> reduce(mul, nums) 6
Python 3 Hack
In regards to approaches such as [total := total + x for x in [1, 2, 3, 4, 5]]
This is a terrible idea. The general idea of emulate sum()
using a list comprehension goes against the whole purpose of a list comprehension. You should not use a list comprehension in this case.
Python 2.5 / 2.6 Hack
In Python 2.5
/ 2.6
You could use vars()['_[1]']
to refer to the list comprehension currently under construction. This is horrible and should never be used but it's the closest thing to what you mentioned in the question (using a list comp to emulate a product).
>>> nums = [1, 2, 3] >>> [n * (vars()['_[1]'] or [1])[-1] for n in nums][-1] 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With