# feature request: mul

Michele Simionato mis6 at pitt.edu
Wed Jun 11 23:01:15 CEST 2003

```Steven Taschuk <staschuk at telusplanet.net> wrote in message news:<mailman.1055356409.24319.python-list at python.org>...
> Quoth Michele Simionato:
>   [...]
> > 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()
>
> Imho this is an abuse of sum().

I will not even try to say that this is not an abuse ;)

> Note that it depends on exactly
> which true and false values are used:
>
>     >>> condition = [1, -1]
>     >>> if condition[0] or condition[1]:
>     ...     print 'foo'
>     ...
>     foo
>     >>> if sum(condition):
>     ...     print 'foo'
>     ...
>     >>>
>
> This kind of thing could make for subtle bugs if you get into the
> habit of thinking of 'sum(L)' as a logical instead of an
> arithmetic operation.

It is difficult to get in this habit since the name 'sum' makes clear
that you are summing numbers; I don't think it is really dangerous.
To me 'condition' is an iterable of predicates with values True or
False, I would not certainly consider condition=[1,-1] a good
candidate.

The point is that there is not a builtin multi_or/multi_and.
I am not advocating it, the use case base is too little for
two new builtins, IMHO.

> (If we had a boolean type which was unrelated to ints, and that
> boolean algebra, and ints and booleans could not be added without
> explicit conversion, then I'd be happy with using sum() on a list
> of booleans.  But this is not the case.)
>
> Another, much more minor, matter: sum() doesn't short-circuit.  I
> don't imagine this would matter unless len(condition) is quite
> large.

Agreed.

>   [...]
> > if mul(condition): # multi_and
> >    dosomething()
>
> If a mul() existed, this would be less prone to bugs than the
> corresponding use of sum(), but it's still not a reliable way to
> rewrite the series of ands; for example, consider
>     condition = ['foo', '']
>
>   [...]
> > 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.
>
> It would naturally complement 'sum', though I wonder whether
> 'product' wouldn't be a better name.  ('mul' is parallel to 'add',
> not 'sum'.)

You are right. 'product' would be fine for me.

> I'm not sure it's commonly enough needed to deserve a built-in,
> though.  If sum, min and max get moved out to a module, I'd
> certainly be in favour of a 'product' function too.  But in no
> case would I want to use these functions for boolean algebra.
>
>   [...]

I understand your motivations; I also would use very rarely this construct.
BTW, I like that 'sum' is a built-in.

Michele

```