List comprehensions, like functions, return values. They can even initialize and accumulate variables.
Initialization in these comprehension takes the form j for j in (n,) where n is any value and is equivalent to the j = n statement. Initialization happens only once at the top level of these comprehensions. Accumulation has the form of [j for j in (ji,)] which is equivalent to j *= i where can be any associative operator and i any value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | nl= (2,3,6,18)
# The sum comprehension
[ [ [j for j in (j+i,) ] for i in nl] for j in (0,) ] [0][-1][0]
# results in 29 or [[[2], [5], [11], [29]]] without [0][-1][0] at the tail
# the product comprehension
[ [ [j for j in (j*i,)] for i in nl ] for j in (1,) ] [0][-1][0]
# results in 648 when nl = (2,3,6,18)
# a factorial comprehension
fac= 6
[ [ [j for j in (j*i,)] for i in range(2,fac+1)] for j in (1,)] [0][-1][0]
# results in 720
|
I dont know of what practical use anonymous list comprehension functions are. They suffer the same weaknesses that is causing the removal of reduce from Python. The sum and product functions are better except I cant find the product function in my Python.
Why all the nested list comprehensions so that you need [0][-1][0] at the end? Why don't you just use multiple fors in the same list comprehension? Then you only need the final [-1]:
Thanks. I am astounded. I so wanted what you so elegantly achieved. To make them work you had to swap the left and right for clauses to remove the nesting. I very incorrectly assumed that would not work. Your functions are so nice and easy they might even find use. You could be the DeMorgan of Python list comprehensions.
(Sorry for the typo: the first 'comprehension' should have ended in 's')
The pattern with prefix functions. And, the pattern works just as effectly with prefix functions
And with predicates.