feature request: mul

Alex Martelli aleax at aleax.it
Thu Jun 12 04:54:58 EDT 2003


Michele Simionato wrote:

> I like the new builtin 'sum', actually I missed it from my very first
> Python program (I was doing hystograms at that time). Here is the
> question: is there any hope to have a corrisponding 'mul' in the near
> future?

No, there isn't.  Indeed, that one issue was the key point in the
python-dev discussion of the sum built-in when I proposed it: would
introducing 'sum' start a "slippery slope" continuing with 'product'
and ending who knows where?  Fortunately, sanity prevailed.  'sum'
accounts for maybe 80-90% of the uses of 'reduce' and similar loops,
is an absolutely elementary functionality that beginners _expect_ in
the language (and indeed get suprised at _not_ finding), and has a
perfectly natural and attractive name (not by chance: summing up a
set of numbers is the most common arithmetic operation in everyday
life, so _of course_ natural languages have good ways to name it!).

'product' (or shold it be 'mul', or ...?) has absolutely none of these
advantages and is NOT going to become a Python built-in, ever.


> Of course, you could use 'mul' to compute factorials, bu my motivation is
> mainly for logical constructs.
> At the present, instead of
> 
> if condition[0] or condition[1] or ....  or condition[42]:
>     dosomething()
> 
> I can use (using a comment to make crystal clear what the code is doing)
> 
> if sum(condition): # multi_or
>    dosomething()

Very tricky though -- you have to ensure that each of the items of
list 'condition' is 0 or 1, and not some negative value that might
erroneously "cancel out" other positive true values.  Personally, I
prefer to have non-built-in auxiliary functions when I need these
kinds of constructs repeatedly:

def anyOf(conditions):
    for c in conditions:
        if c: return c
    return False
firstTrue = anyOf

def allOf(conditions):
    for c in conditions:
        if not c: return c
    return True
firstFalse = allOf

(I'll use the synonyms firstTrue and firstFalse when I actually care
about the exact value of the first true/false item, the names anyOf
and allOf when I only care about the truth value of the latter).


> Apart for boolean algebra, I think a 'mul' with
> the signature
> 
> mul(iterable, start=1)
> 
> would naturally complement 'sum'. Moreover,
> the implementation would be trivial and I don't
> see why we should not have it.

Because its use would be far too rare to warrant a built-in.  And
encouraging people to multiply (or add) booleans would be a bad
side effect, not a good one.


Alex





More information about the Python-list mailing list