What is the most efficient way to test for False in a list?
carsten at uniqsys.com
Sun Jul 8 22:24:10 EDT 2007
On Sun, 2007-07-08 at 18:32 -0700, Evan Klitzke wrote:
> On 7/8/07, lex <alexander.somma at gmail.com> wrote:
> > Of course there is the always the iteration method:
> > list = [1, True, True, False, False, True]
> > status = True
> > for each in list:
> > status = status and each
> > but what is your best way to test for for False in a list?
> In general, you can just do:
> if something in list:
Caution! This tests whether at least one entry in 'list' is *equal* to
'something'. It is very unusual to want to test whether an object is
equal to True (or False). Usually one simply wants to know whether the
bool() value of that object is True (or False).
While it makes no difference with the contrived example above, in
general your suggestion may give unexpected results. The following
variant, making use of a generator expression to take the bool() of each
entry, will always work correctly:
if False in (bool(x) for x in list):
But then again, in Python 2.5 you can use all() as suggested by Paul
if not all(list):
I'd also like to point out, since nobody has so far, that 'list' is a
terrible name for a list because it shadows the name for the list type.
More information about the Python-list