Hi everyone, welcome back. Today, we will be going over the any() function in Python and see how it works. The any() function is a built in function and can be used to check if any of the values within an iterable object is a true value. The any() function returns a boolean value. With this introduction out of the way, let’s get into it.
Any() Function
Let’s see how the any() function works:
list = [True, False]
print(any(list))Output:
True
As we can see in the example above, we created a list containing a true value and are printing the result of the any() function being used on it. Our output verifies that our list does contain a true value. Let’s see what it does if we do not have any true values:
list = [False, False]
print(any(list))Output:
False
As expected, we have a false in our output. verifying that our list does not contain any true values.
More List Examples
This also works with the numerical values of 0 and 1 as well. 0 being false, and 1 being true. Let’s see some examples. List containing a true value:
list = [0, 1]
print(any(list))Output:
True
List not containing a true value:
list = [0, 0]
print(any(list))Output:
False
More Examples With The Any() Function
Example with a tuple containing a true value:
tuple = (0, True)
print(any(tuple))Output:
True
Example with a tuple not containing a true value:
tuple = (0, False)
print(any(tuple))Output:
False
Example with a set containing a true value:
set = {0, True}
print(any(set))Output:
True
Example with a set not containing a true value:
set = {0, False}
print(any(set))Output:
False
Example with a dictionary containing a true value:
dictionary = {0 : "False", True : "True"}
print(any(dictionary))Output:
True
Example with a dictionary not containing a true value:
dictionary = {0 : "False", False : "True"}
print(any(dictionary))Output:
False
Conclusion
This is it for the any() function examples. It’s a straight forward function that checks whether or not an iterable object contains a true value. I hope this helps. Thanks for reading.