Ekeyme Mo Ekeyme Mo - 3 months ago 17
Python Question

Οpposite of any() function

The Python built-in function

any(iterable)
can help to quickly check if any
bool(element)
is
True
in a iterable type.

>>> l = [None, False, 0]
>>> any(l)
False
>>> l = [None, 1, 0]
>>> any(l)
True


But is there an elegant way or function in Python that could achieve the opposite effect of
any(iterable)
? That is, if any
bool(element) is False
then return
True
, like the following example:

>>> l = [True, False, True]
>>> any_false(l)
>>> True


Conclusion



Both @JackAidley's and @deceze's answer are pretty.

@deceze's answer are more generally applicable, but @JackAidley's has a better performance(according to dawg's answer and test my myself).

So I accept @JackAidley's answer as the best. But people should notice that
all
returns True on empty iterable.

Answer

There is also the all function which does the opposite of what you want, it returns True if all are True and False if any are False. Therefore you can just do:

not all(l)
Comments