testing array of logicals

Alex Martelli aleax at mac.com
Thu Jul 13 00:34:05 EDT 2006


John Henry <john106henry at hotmail.com> wrote:

> Hi list,
> 
> Is there a more elagant way of doing this?
> 
> # logflags is an array of logicals
> test=True
> for x in logflags:
>    test = test and x
> print test

test = sum(bool(x) for x in logflags)==len(logflags)

is yet another possibility (without the effectiveness of
shortcircuiting, just like the quoted approach).  Some might prefer

test = not sum(not x for x in logflags)

but that's starting to border on the obscure;-).

If by "logicals" you mean "bool" instances (True and False) only, then

test = sum(logflags) == len(logflags)

is simpler and fast than, but equivalent to, my first suggestion.


Alex



More information about the Python-list mailing list