Comment on draft PEP for deprecating six builtins
Alex Martelli
aleax at aleax.it
Mon Apr 29 04:05:32 EDT 2002
David Eppstein wrote:
> In article <aaim48$7fd$1 at bob.news.rcn.net>,
> "Raymond Hettinger" <python at rcn.com> wrote:
>
>> The functionals (map, filter, and reduce) had greater importance
>> prior to the introduction of list comprehensions which are now the
>> preferred (and more readable) approach.
>
> Map and filter, I can see substituting with list comprehensions.
> But can you tell me how to use a list comprehension in place of reduce?
Only kludgily, today (skipping the extra test needed to handle
a missing 'starter'):
def myreduce(function, sequence, starter):
return [starter for item in sequence
for starter in (function(starter,item),)][-1]
>>> from operator import add
>>> myreduce(add, range(10), 0)
45
>>>
You can replace any use of built-in reduce with a list comprehension
based on these ideas -- if starter is missing you need a further
'for starter in sequence[:1]' as the first for clause of the LC
and of course 'for item in sequence[1:]' as the second for clause.
But I do think this IS kludgy, much like saying that Python DOES
have assignment-within-expression because where in C you might
code
while((next=makenext())) process(next);
in Python you might code
while [next for next in (makenext(),)][0]: process(next)
"[x for x in (y,)][0]" DOES have just the same semantics as a
hypothetical "x=y acceptable as part of an expression". But it
does appear to me to be a kludgy exploit of something of an
"implementation accident" of list comprehensions.
Alex
More information about the Python-list
mailing list