builtin functions for and and or?

George Sakkis gsakkis at rutgers.edu
Sun Feb 13 17:27:11 EST 2005


"Roose" <b at b.b> wrote in message news:y9PPd.4645$ZZ.528 at newssvr23.news.prodigy.net...
> I need this a lot: a one line way to do a n-ary and or 'or'.
>
> e.g.,
>
> result = True
> for x in L:
>   if not boolean_function(x):
>     result = False
>
> or
>
> >>> reduce(operator.__and__, [boolean_function(x) for x in L)
>
> So usually I just write a little function any( L, boolean_function =
> identity ) or all( ... ).  But I am kind of sick of doing that all the
> time -- does it exist anywhere in the Python libraries?  It seems really
> common to me.
>
> The first way isn't satisfactory because it takes so many lines for what is
> essentially one "primitive" operation.  The second way isn't great because
> it is not as readable and many readers don't like to see reduce, even if it
> is a common idiom like that.  Also I don't believe it short circuits.


You're right, it doesn't short circuit, as most of the examples posted above. Here's one that it
does:

from itertools import ifilter, dropwhile

def any(pred, iterable):
    try: ifilter(pred,iterable).next()
    except StopIteration: return False
    else: return True

def all(pred, iterable):
    try: dropwhile(pred,iterable).next()
    except StopIteration: return True
    else: return False


George





More information about the Python-list mailing list