Idea for reduce (Re: Question regarding a recent article on informit.com)

Beni Cherniavsky cben at techunix.technion.ac.il
Fri Mar 21 04:46:03 EST 2003


On 2003-03-21, Greg Ewing (using news.cis.dfn.de) wrote:

> Ben S wrote:
> > Are there any good tutorials of examples of list comprehension use? In
> > particular, I'm interested in how to replicate the functionality of
> > reduce? Map and filter seem easy to do, though.
>
There is an evil way:

>>> from operator import add
>>> numbers = [1, 2, 3, 4, 5]
>>> reduce(add, numbers)
15
>>> [sum for sum in [0] for n in numbers for sum in [sum + n]]
[1, 3, 6, 10, 15]
>>> [sum for sum in [0] for n in numbers for sum in [sum + n]][-1]
15

The trick is using single-value lists for avriable assignment.
This is not entirely ugly but not readable enough; better don't use it
in your code ;-)

> As has been pointed out, list comprehensions don't (and
> aren't meant to) substitute for reduce, only for map
> and filter.
>
> Something else again would be needed if we wanted a
> reduce-substitute. While I'm far from certain that it
> would be worth it, it's interesting to speculate on what
> a Pythonic reduce-syntax might look like.
>
> We want something that says things like "add up this
> list of numbers". Let's see... if we were to make
> "up" a new (possibly pseudo) keyword...
>
>    from operator import add
>    numbers = [1, 17, 42]
>    total = add up numbers
>
> Howzat look? :-]
>
``sub up`` wouldn't look good :-).  You also need syntax for initial
value.  Most importantly, your syntax still expects a callable -
avoiding that is the main benefit of list comprehensions over `map`.

How about::

    total = (accumulate sum = 0 then sum + n for n in numbers)

Not brilliant either...

I'd vote this YAGNI since the equivallent loop is more readable
anyway::

    total = 0
    for n in numbers:
        total += n

For inspiration on baroque loop design, look at Common Lisp's `loop`
macro.  It has all this and more, for all cases you want, if you want
them, else it still has it :-].

-- 
Beni Cherniavsky <cben at tx.technion.ac.il>
[Sorry for some recent duplicate posts...  My news gateway is bogus]





More information about the Python-list mailing list