Search code examples
pythonlistpython-3.xconventions

Branch on boolean statement applied to each element of an iterable


Is there a Pythonic way to say "is this true of any element in this iterable"? Or, in other words, is there a cleaner version of this:

if [True for x in mylist if my_condition(x)]:
    ...

Solution

  • 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 generator expression instead of list comprehension, you don't need to evaluate the all items.