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 :
l
>>> reduce(int.__mul__,[1,2,3])
6
C:\Users\Henry>python -m timeit -s "" "reduce(int.__mul__,range(10000))"
1000 loops, best of 3: 910 usec per loop
C:\Users\Henry>python -m timeit -s "from operator import mul" "reduce(mul,range(10000))"
1000 loops, best of 3: 399 usec per loop
C:\Users\Henry>
It is possible to achieve by using lambda with list comprehension Since we can't assign a value in list comprehension we go with lambda
Solution:
>>> (lambda number_list, sum=0:[sum for number in number_list for sum in [sum + number]][-1])([1, 2, 3, 4, 5])
>>> 15
I might be a bit late for this discussion, but I would like to mention that list comprehentions are turing complete, and thus this can be done with a list comprehention!
This however is messy, so I have used the following trick, which makes a cummulative array, and returns the last element
def sum(l):
return [c[-1] for c in [[0]] for e in l if c.append(c[-1] + e) is None][-1]
Starting Python 3.8
, and the introduction of assignment expressions (PEP 572) (:=
operator), we can use and increment a variable within a list comprehension and thus reduce a list to the sum of its elements:
total = 0
[total := total + x for x in [1, 2, 3, 4, 5]]
# 15
This:
total
to 0
total
is incremented by the current looped item (total := total + x
) via an assignment expressionSomething like this:
>>> a = [1,2,3]
>>> reduce(lambda x, y: x*y, a)
6