Search code examples
pythonfunctional-programmingcallbackany

any() function in Python with a callback


The Python standard library defines an any() function that

Return True if any element of the iterable is true. If the iterable is empty, return False.

It checks only if the elements evaluate to True. What I want it to be able so specify a callback to tell if an element fits the bill like:

any([1, 2, 'joe'], lambda e: isinstance(e, int) and e > 0)

Solution

  • How about:

    >>> any(isinstance(e, int) and e > 0 for e in [1,2,'joe'])
    True
    

    It also works with all() of course:

    >>> all(isinstance(e, int) and e > 0 for e in [1,2,'joe'])
    False