Accumulate function in python

dhruvbird dhruvbird at gmail.com
Mon Jul 26 16:24:28 EDT 2010


On Jul 21, 8:17 pm, John Nagle <na... at animats.com> wrote:
> On 7/19/2010 9:56 AM, dhruvbird wrote:
>
> > On Jul 19, 9:12 pm, Brian Victor<homeusen... at brianhv.org>  wrote:
> >> dhruvbird wrote:
> >> Having offered this, I don't recall ever seeing reduce used in real
> >> python code, and explicit iteration is almost always preferred.
>
> > Yes, even I have noticed that reduce is a tad under-used function.
>
>      Yes, I had a use case for it once, but it wasn't worth the trouble.
> "map" is often useful, but "reduce", not so much.
>
>      Python isn't really a functional language.  There's no bias toward
> functional solutions, lambdas aren't very general, and the performance
> isn't any better.  Nor is any concurrency provided by "map" or "reduce".
> So there's no win in trying to develop cute one-liners.

Yes agreed.

However, there is:

1. now scope for optimization (for example returning generators
instead of lists) at every stage if using functions -- these functions
can be internally changed as long as the external guarantees they
provide remain essentially unchanged.

2. readability wins because you express your intent (operations)
rather than anything else.
For example, if I want the product of the square roots of all odd
integers in an array, I can say:
answer = reduce(product, map(math.sqrt, filter(lambda x: x%2 == 0,
some_array_with_ints)))

While I agree that python may not have been initially seen as a
functional language, it is powerful and flexible enough to be one or
at least decently support such paradigms.

Regards,
-Dhruv.



More information about the Python-list mailing list