In this tutorial we will learn about python any() method and its uses.
What is Python any() Method?
The any() is a built-in method available in python, which will return True if any element is present in an iterable like list, tuple, set, dictionary, or loop in python.
If the iterable is empty or any elements are not present, the any() method will return False.
Syntax of any() method.
Python any() Parameter
The any() method will take an iterable, including list, tuple, set, dictionary, string, and loop in python.
Let’s see a basic example of any() method.
Example 1: using any() on python Lists.
The Output will be as follows.
As we can see, the first list is not empty. That’s why any() method is returning True because its contents elements and the second list are empty, hence returning False.
Note that any() method will consider 0 and False as a Null value, hence returning False in the third list.
The any() method works similarly for tuples and sets like lists.
Example 2: Using any() on Python Strings
Example 3: How to check if a dictionary is empty in python?
The output will be as follows:
In the case of dictionaries, if all keys (not values) are false or the dictionary is empty, any() returns False. If at least one key is true, any() returns True.
Rules of any() method
- The any() method will return a boolean as a value.
- If there is at least one element in an iterable that is true, any() method will return True.
- If all elements in an iterable are False or an iterable is empty, then any() method will return False.
- If all the values are true in iterable, any() will return True.
- If all the values are false in iterable, any() will return False.
- If one value is true and others are false, any() will return True.
- If one value is false and others are true, any() will return True.
- If the iterable is empty, any() will return False.