extended list comprehensions

Bengt Richter bokr at oz.net
Mon May 27 17:03:37 EDT 2002


On 27 May 2002 15:15:54 +0200, Bernhard Herzog <bh at intevation.de> wrote:

>fxj at hotmail.com (F. Jamitzky) writes:
>
>> It would be great to have something like a list comprehension for the
>> reduce function. It would work in the same way as the comprehension
>> for the map function, which is:
>> 
>> [foo(x) for x in xs]      <-is the same as->       map(foo,xs)
>> 
>> and maybe it could be written as:
>> 
>> {y=y+x for x in xs}      <-would be->         reduce(operator.add,xs)
>
>
>Well, one could mimic reduce with the side-effects of a list
>comprehension:
>
>>>> y = 0
>>>> xs = range(10)
>>>> [0 for x in xs for y in [y + x] if 0]
>[]
>>>> y
>45
>
>Not recommended, though :-)
>
That is really evil ;-) Enough so to want a private scope
to prevent side effects for list comprehensions.

I wonder how much code would break, not counting horrible examples
concocted just for the sake of messing around.

BTW, I wonder if reduce would get more use if it had a more suggestive
name and mnemonic keyword arguments, e.g.,

 >>> def accumulate(**kw):
 ...     return reduce(
 ...         kw.get('f_acc_delta', lambda a,d: a+d),
 ...         kw.get('seq',[]),
 ...         kw.get('start_with', 0)
 ...     )
 ...
 >>> accumulate(seq=range(10))
 45
 >>> accumulate(seq=range(4),f_acc_delta=lambda a,d: a+d*d)
 14
 >>> accumulate(seq='abc', start_with='XXX:')
 'XXX:abc'

or maybe def accumulate(seq, **kw): ...

Regards,
Bengt Richter



More information about the Python-list mailing list