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,) ] [-1] # results in 29 or [[, , , ]] without [-1] at the tail # the product comprehension [ [ [j for j in (j*i,)] for i in nl ] for j in (1,) ] [-1] # 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,)] [-1] # 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.