A boolean branch is applied to each element of an iterable

Is there a pythonic way of saying, “Is this true for any element in this iterable”? Or, in other words, there is a cleaner version of this:

if [True for x in mylist if my_condition(x)]:
    ...
+4
source share
1 answer

You can use any:

>>> mylist = [1, 2, 3]
>>> any(x > 4 for x in mylist)
False
>>> any(x % 2 == 0 for x in mylist)
True

if any(my_condition(x) for x in mylist):
    ....

NOTE. Using the expression generator instead of understanding the list, you do not need to evaluate all the elements.

+5
source

Source: https://habr.com/ru/post/1570528/


All Articles