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 1:

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

Solution 2:

any function returns True when any condition is True.

>>> any(isinstance(e, int) and e > 0 for e in [0 ,0, 1])
True # Returns True because 1 is greater than 0.


>>> any(isinstance(e, int) and e > 0 for e in [0 ,0, 0])
False # Returns False because not a single condition is True.

Actually,the concept of any function is brought from Lisp or you can say from the function programming approach. There is another function which is just opposite to it is all

>>> all(isinstance(e, int) and e > 0 for e in [1, 33, 22])
True # Returns True when all the condition satisfies.

>>> all(isinstance(e, int) and e > 0 for e in [1, 0, 1])
False # Returns False when a single condition fails.

These two functions are really cool when used properly.

Solution 3:

You should use a "generator expression" - that is, a language construct that can consume iterators and apply filter and expressions on then on a single line:

For example (i ** 2 for i in xrange(10)) is a generator for the square of the first 10 natural numbers (0 to 9)

They also allow an "if" clause to filter the itens on the "for" clause, so for your example you can use:

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

Solution 4:

Slight improvement to Antoine P's answer

>>> any(type(e) is int for e in [1,2,'joe'])
True

For all()

>>> all(type(e) is int for e in [1,2,'joe'])
False