How to Use the Python any() Function
In this tutorial, you will learn how to use the Python any() function, which returns True if any of the given iterable elements, such as a list, tuple, or dictionary, is True. Otherwise, it returns False. If the iterable is empty, any() returns False.
Python any() Syntax
The syntax of the any() function is as follows:
any(iterable)
The any() function Parameter
- Iterable: Required. It can be a list, tuple, set, dictionary, etc.
Examples
Check if any item in the list is True:
Example 1:
list = ["Apple", "Orange", "Kiwi", 120, 430] check = any(list) print(check)
Output:
True
Example 2:
list = [1>2, False, 2==2, 3<2, False] check = any(list) print(check)
Output:
True
Check whether any of the items in the tuple are True:
The following code returns True if any item in the tuple is True:
tuple = (1>2, 2>3, 30>30.5, False) check = any(tuple) print(check)
Output:
False
Check if any item in the set is True:
The following code returns True if any item in the set is True:
set = {False, 100 > 200, "B"=="B", 240 > 241} check = any(set) print(check)
Output:
True
Check if any of the entries in the dictionary are True.
The following code returns True if any of the dictionary entries are True:
dict = { False: "This key of the dictionary is False!", 1>2: "This key of the dictionary is False!", 2>1: "This key of the dictionary is True!" } check = any(dict) print(check)
Output:
True
Note that the any() function checks whether any of the keys in the dictionary is True, not the value.
Check if any item in the empty list is True:
list = [] check = any(list) print(check)
Output:
False
Summary
In this tutorial, you learned how to use Python's any() function, which returns True if any of the given iterable elements, such as a list, tuple, or dictionary, is True. Otherwise, it returns False. If the iterable is empty, any() returns False.