In this post, we will be looking into any() and all() functions in Python.
First, let us discuss the any() function.
The any() function takes an iterable as an argument : any(iterable).
The iterable can be a list, tuple or dictionary.
The any() function returns 'True' if any element in the iterable is true.
However, it returns 'False' if the iterable passed to the function is empty.
This function is similar to the code block below
def any(iterable): for element in iterable: if element: return True return False
Below is an example of using any for returning 'True' for numbers greater than 3.
Here we have used list comprehension to keep the code simple.
list=[2,3,4,5,6,7] print(any([num>3 for num in list]))
The output is 'True' as 4,5,6 and 7 are greater than 3.
Next, we look into the all() function.
The all() function also takes an iterable as an argument: all(iterable).
all() function returns 'True' only if all the items in the iterable are true.
Even if one item is false, it returns 'False'. However, if the iterable is empty, it returns 'True'.
all() function is similar to the code block below
def all(iterable): for element in iterable: if not element: return False return True
Below is an example of using any for returning True for numbers greater than 3.
list=[1,2,3,3] print(all([num>3 for num in list]))
The output is False as no number is greater than 3 in the provided list.
- In dictionaries, both all() and any() functions to check the key for returning True or False and not the values.