any() function in Python with a callback
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Breezy Bay
--
Chapters
00:00 Any() Function In Python With A Callback
00:22 Accepted Answer Score 159
00:36 Answer 2 Score 22
01:11 Answer 3 Score 15
01:39 Answer 4 Score 9
01:53 Answer 5 Score 6
02:23 Thank you
--
Full question
https://stackoverflow.com/questions/2012...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #functionalprogramming #callback #any
#avk47
ACCEPTED ANSWER
Score 159
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
ANSWER 2
Score 22
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.
ANSWER 3
Score 15
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)
ANSWER 4
Score 6
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:
def any_lambda(iterable, function):
  return any(function(i) for i in iterable)
In [1]: any_lambda([1, 2, 'joe'], lambda e: isinstance(e, int) and e > 0
Out[1]: True
In [2]: any_lambda([-1, '2', 'joe'], lambda e: isinstance(e, int) and e > 0)
Out[2]: False
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():
def any_lambda(function, iterable):
  return any(function(i) for i in iterable)