[Python-Dev] Fwd: summing a bunch of numbers (or "whatevers")

Tim Peters tim.one@comcast.net
Mon, 21 Apr 2003 23:03:20 -0400

[Greg Ward]
> I can't count the number of times sum() would have been useful to me.  I
> can count the number of times prod() would have been: zero.

Two correct answers.  Good for you, Greg!

> Bitwise and/or en masse seems unnecessary (although I remember being
> quite tickled by the fact that you can do bitwise operations on strings
> in Perl -- whee, fun! -- when I was young and naive).
> However, there have been a number of occasions where I wanted *logical*
> and/or en masse: are any/all elements of this list true/false?  On
> several occasions I tried to do it in one super-clever line of code
> using reduce(), and I think I even succeeded once.  But usually I give
> up and make it a loop.  IMHO *this* is likely to be the feature people
> start asking for after they decide sum() is handy.

def alltrue(seq):
    return sum(map(bool, seq)) == len(seq)

def atleastonetrue(seq):
    return sum(map(bool, seq)) > 0

> ...
> PS. my nominations for removal in Python 3.0: reduce() and filter().

reduce() is still in Python?!  Brrrr.

filter() is hard to get rid of because the bizarre filter(None, seq) special
case is supernaturally fast.  Indeed, time the above against

def alltrue(seq):
    return len(filter(None, seq)) == len(seq)

def atleastonetrue(seq):
    return bool(filter(None, seq))

Let me know which wins <wink>.