Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (4k points)

In the python docs page for any, the equivalent code for the any() function is given as:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

How does this function know what element I wanna test if call it in this form?

any(x > 0 for x in list)

From the function definition, all I can see is that I'm passing an iterable object. How does the for loop know I am looking for something > 0?

1 Answer

0 votes
by (8.7k points)
edited by

Let’s consider any(itr), where it refers to any list, dictionary, or function and considered to be iterable.

The Boolean value returned by any function in the different scenario are:

  • Returns True if any of the element of iterable is true
  • Returns False if all the elements of iterable are false or the iterable is empty.

If you pass any function as any(x > 0 for x in list)

Then this work on the basis of generator expression uses it as iterable and when the function iterates the element till it gets its first true element and returns True for X>0.

check out the Python course by Intellipaat to get more insights about it.

Related questions

0 votes
1 answer
+8 votes
2 answers
0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.6k points)

Browse Categories

...