Python any() function:
The Python any() function returns true if any of the elements in iterable(List, Dictionary, Tuple, Set) is true or non zero. However, if all values are zero or false, this method returns false. Moreover, this method returns false for an empty iterable object.
Signature
The signature for the any() method is as shown below. Iterable can be a list, dictionary, tuple, or set. The boolean value returned by the function is stored in variable r.
r=any(iterable)
Parameters and return type
- Here, The any() method takes an iterable object as a parameter.
- However, it returns the boolean value True or False.
Python Built-in Function any Examples:
Example 1: In this example, let us take a list l
and Set s
containing some numbers.
#Initializing
l=[0,1,0,0,0]
s={0,0,0,0,0}
# Using any method and printing
r=any(l)
print("List contains any non zero values - ",r)
r=any(s)
print("Set contains any non zero values - ",r)
Output
List contains any non zero values - True
Set contains any non zero values - False
In the above example, the list l
contains most of zeros and only one non zero value; because of this, the function returns True, whereas the Set s
contains all zero values; hence it returns value False.
Example 2: In this case, We will take a dictionary to demonstrate any() function.
#Initializing
d1={0:"Zero",2:"Two",3:"Three"}
d2={}
#Using any method and printing
r=any(d1)
print("Dictionary d1 contains any non zero elements",r)
r=any(d2)
print("Dictionary d2 contains any non zero elements",r)
Output
Dictionary d1 contains any non zero elements True
Dictionary d2 contains any non zero elements False
As we can see, in the above output, the any function returns True, although one of the keys has a zero value. However, it returns False if it doesn’t contain any values.
Example 3: In this example, We will print the elements of two sets if any of the values in the set
are non zero; otherwise, we will print an error message. Here, Set s1
has values, whereas Set s2
is an empty set.
#Initializing
s1={10,20,30,40,50}
s2={}
#Using any method and printing
if any(s1):
print("Set s1 = ",s1)
else:
print("Set s1 doesn't contain any non zero elements")
if any(s2):
print("Set s2 = ",s2)
else:
print("Set s2 doesn't contain any non zero elements")
Output
Set s1 = {40, 10, 50, 20, 30}
Set s2 doesn't contain any non zero elements
Conclusion
The any() function returns a true value if the iterable contains at least one non-zero value. However, it returns false otherwise.
References
Happy Learning 🙂