Python Tutorial Was: Guido's regrets: filter and map

Mel Wilson mwilson at the-wire.com
Tue Nov 26 11:10:49 EST 2002


In article <mailman.1038295415.22435.python-list at python.org>,
Terry Hancock <hancock at anansispaceworks.com> wrote:
> [ ... ]                                           (BTW, I never used
>reduce, never understood what it was good for, and don't immediately
>see how it can be done using list-comps -- would be genuinely interested
>in seeing a couple of example if anyone's willing).

   I don't see `reduce` replacable by list comprehension
because `reduce` doesn't generally return a list.  Reduce is
what you could use to implement (e.g.) product of a list of
items:

        the_product = reduce (lambda x,y: x*y, the_list, 1)

`reduce` is meant to summarize or boil down a list into a
single item.  My using `reduce` here a while ago to get a
list of Fibonacci numbers given a range was an anomaly.

>As for the pain of thinking up a name -- I think it's actually a good
>sign. It shows you care.  Good names are a real benefit to your own
>future self and to anyone else who must read your code.

   But I don't always care.  F'rinstance, defining a
function

        def multiply_two_numbers (x,y): return x * y

would be silly.  'multiply_two_numbers' is longer than
'lambda x,y: x*y' and if you read it in my reduce call
you'd be honour bound to skip out of line and reassure
yourself that the function really did multiply two numbers,
caused no important side effects, etc.  (in the first draft
of this post, I'd typed 'return x * 7', but I fixed it.)

`reduce` and `lambda`:  cryptic, but great for locality of
reference.

        Regards.        Mel.



More information about the Python-list mailing list