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

Carl Banks pavlovevidence at gmail.com
Tue Oct 30 00:18:43 CET 2007


On Oct 29, 6: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))

Probably not, because it doesn't take advantage of short circuiting.
You could bail out of alltrue as soon as the first item you see is
false, but your version applies f to every item in the list.  I would
suggest the most straightforear way is the best:

def alltrue(f,l):
    for item in l:
        if not f(item):
            return False
    return True


On Python 2.5, you could do this:

all(f(x) for x in l)


Carl Banks




More information about the Python-list mailing list