The any() function in Python returns True if any elements of the iterable are True.
The any() function takes an argument which is the iterable e.g. a list, dictionary, string, tuple. For example:
If iterable is empty then any() function returns False.
How to use any() function
The general way for using the any() function is:
An example of using lists in any function
The example below shows using lists in the any() function as iterator argument. Two lists are created; one that contains a few items and the other is empty.
The code:
#A demo of any() function a_list = [2,4, "", 6, "Python"] b_List = [] a_bool = any(a_list) b_bool = any(b_List) print(a_bool) print(b_bool)
The result:
True
False
As the second list is empty, the any() function returned False.
On the other hand, as 2, 4, 6 and “Python” will evaluate as True, so any() function returned True for the first list.
Using True/False values in a list example
This example should make things even clear:
bool_list1 = [True, True, False, True] bool_list2 = [False, False, False, False] bool_list3 = [True, True, False, True] print(any(bool_list1)) print(any(bool_list2)) print(any(bool_list3))
The result:
True
False
True
Similarly, if you have an iterator that contains items like None, 0, ‘’, -0, 0.0 then any() function will also return False. See the example with a list below:
false_list = [None, 0, False, '', 0.0] print(any(false_list))
Output:
The reason is all these items i.e. 0, 0.0, -0, False, and None are evaluated as False. As any() function could not find any item that is evaluated as True, so the result is False.
If we had just one item that evaluates as True then see the result:
a_list = [None, 0, False, '', 0.0, -0, 1] print(any(a_list))
The output:
Because this time 1 is evaluated as True.
An example of any() function with dictionary
The example below is using three dictionaries to show how any() function works with a dictionary:
a_dict = {0: 'False'} b_dict = {0: ''} c_dict = {0: None} e_dict = {1: None} f_dict = {"str": ''} g_dict = {"num": 0} print(any(a_dict)) print(any(b_dict)) print(any(c_dict)) print(any(e_dict)) print(any(f_dict)) print(any(g_dict))
The result:
False
False
False
True
True
True
An example with string
As such, the string is also an iterator in Python; you may also use strings in the any() function. The example below shows output as using string objects in the any() function.
str1 = "Hellow World" str2 = "" str3 = "0" str4 = "None" print(any(str1)) print(any(str2)) print(any(str3)) print(any(str4))
The output of above code: