builtin functions for and and or?

Steven Bethard steven.bethard at gmail.com
Sun Feb 13 17:16:08 EST 2005


Brian Beck wrote:
> Roose wrote:
> 
>> I need this a lot: a one line way to do a n-ary and or 'or'.
> 
> Here's a one-liner for the n-ary and:
> 
> bool(min(bool(x) for x in L))
> 
> py> bool(min(bool(x) for x in [1, 1, 1, 0]))
> False
> py> bool(min(bool(x) for x in [1, 1, 1, 1]))
> True
> py> bool(min(bool(x) for x in ['a', '', 'b', 'c']))
> False
> py> bool(min(bool(x) for x in ['a', 'b', 'c', 'd']))
> True

Another alternative:

not False in (bool(x) for x in L)

py> not False in (bool(x) for x in [1, 1, 1, 0])
False
py> not False in (bool(x) for x in [1, 1, 1, 1])
True
py> not False in (bool(x) for x in ['a', '', 'b', 'c'])
False
py> not False in (bool(x) for x in ['a', 'b', 'c', 'd'])
True

Note that this should short-circuit, where min won't.

Steve



More information about the Python-list mailing list