"and" and "or" on every item in a list

Raymond Hettinger python at rcn.com
Mon Oct 29 19:12:52 EDT 2007


On Oct 29, 3:57 pm, GHZ <geraint.willi... at gmail.com> wrote:
> Is this the best way to test every item in a list?
>
> def alltrue(f,l):
>     return reduce(bool.__and__,map(f,l))
>
> def onetrue(f,l):
>     return reduce(bool.__or__,map(f,l))
>
>
>
> >>> alltrue(lambda x:x>1,[1,2,3])
> False
>
> >>> alltrue(lambda x:x>=1,[1,2,3])
> True

In Py2.5, you can use the builtin any() and all() functions.

In Py2.4, use the recipes from the itertools module:

def all(seq, pred=None):
    "Returns True if pred(x) is true for every element in the
iterable"
    for elem in ifilterfalse(pred, seq):
        return False
    return True

def any(seq, pred=None):
    "Returns True if pred(x) is true for at least one element in the
iterable"
    for elem in ifilter(pred, seq):
        return True
    return False

def no(seq, pred=None):
    "Returns True if pred(x) is false for every element in the
iterable"
    for elem in ifilter(pred, seq):
        return False
    return True


Raymond




More information about the Python-list mailing list