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)
If you really want to inline a lambda in any() you can do this:
You just have to wrap up the unnamed lambda and ensure it is invoked on each pass by appending the
()
The advantage here is that you still get to take advantage of short circuiting the evaluation of any when you hit the first int
any function returns True when any 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
These two functions are really cool when used properly.
Yo 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:
You can use a combination of
any
andmap
if you really want to keep your lambda notation like so :But it is better to use a generator expression because it will not build the whole list twice.
While the others gave good Pythonic answers (I'd just use the accepted answer in most cases), I just wanted to point out how easy it is to make your own utility function to do this yourself if you really prefer it:
I think I'd at least define it with the function parameter first though, since that'd more closely match existing built-in functions like map() and filter():
How about:
It also works with
all()
of course: