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

Paul Hankin paul.hankin at gmail.com
Mon Oct 29 19:24:44 EDT 2007


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

No. In Python 2.5 there are builtins 'all' and 'any' that do exactly
these. If you're using python <2.5, then you can support shortcut
evaluation - there's no need to check every element once you find a
false in 'all' or a true in 'any'.

--
Paul Hankin




More information about the Python-list mailing list