Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 
like image 657
Emil Ivanov Avatar asked Jan 06 '10 11:01

Emil Ivanov


People also ask

Can a callback function call another function?

Yes. The print( ) function takes another function as a parameter and calls it inside. This is valid in JavaScript and we call it a “callback”. So a function that is passed to another function as a parameter is a callback function.

What are callback functions with an example?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.

Which function is known as callback function?

Any function that is passed as an argument is called a callback function. a callback function is a function that is passed to another function (let's call this other function otherFunction ) as a parameter, and the callback function is called (or executed) inside the otherFunction .

What is the use of any in Python?

Python any() Function The any() function returns True if any item in an iterable are true, otherwise it returns False. If the iterable object is empty, the any() function will return False.


2 Answers

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 
like image 169
Antoine P. Avatar answered Oct 11 '22 12:10

Antoine P.


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.

like image 22
aatifh Avatar answered Oct 11 '22 13:10

aatifh