reduce()--what is it good for?

David C. Fox davidcfox at post.harvard.edu
Mon Nov 10 11:18:58 EST 2003


Alex Martelli wrote:

> Erik Max Francis wrote:
> 
> 
>>But reduce isn't simply intended for adding up numbers.  It's for doing
>>any kind of reduction.
> 
> 
> However, so many of reduce's practical use cases are eaten up by sum,
> that reduce is left without real use cases to justify its existence.
> 

How about

import operator
seq_of_flag_integers = [01020, 02300, 00132] #etc.
reduce(operator.or_, seq_of_integers)

My simple timing tests (cumulative time for 1000 trials, each with a 
sequence of 1000 integers), show no significant difference between the 
above and an alternative using a for loop and |=, but the above is 
clearer to read.

I'm not claiming that the use case above is common, or particularly 
useful.  I'm just pointing out sum doesn't replace reduce unless the 
function being applied is addition.  Addition may be the most common 
case, and in that case, sum is both clearer and faster.  However, that 
doesn't detract from the clarity and usefulness of reduce in the 
remaining cases.

David

P. S. I've seen a lot of talk about removing old features from Python, 
or specifically old built-ins, because of bloat.  Does this "bloat" 
reduce performance, or does it refer to the extra burden on someone 
learning the language or reading someone else's code?





More information about the Python-list mailing list