What is the most efficient way to test for False in a list?

Hrvoje Niksic hniksic at xemacs.org
Mon Jul 9 16:24:46 CEST 2007


Paul McGuire <ptmcg at austin.rr.com> writes:

>> >>> False in [3, 2, 1, 0, -1]
>>
>> True    # no False here>>> all([3, 2, 1, 0, -1])
>>
>> False   # false value present, not necessarily False
>
> I think if you want identity testing, you'll need to code your own;

I'm aware of that, I simply pointed out that "False in list" and
any(list) are not equivalent and where the difference lies.

>>>> any(map(lambda _ : _ is False,[3,2,1,0,-1]))

Note that you can use itertools.imap to avoid the unnecessary
intermediate list creation.  Even better is to use a generator
expression:

>>> any(x is False for x in [3, 2, 1, 0, -1])
False
>>> any(x is False for x in [3, 2, 1, 0, -1, False])
True



More information about the Python-list mailing list