Python any() function checks if at least one element in an iterable (like a list or tuple) is True. It returns True if any element is True; otherwise, it returns False. This function is helpful when you need to know if any condition is met within a collection.
any()
Syntax
result = any(iterable)
result
: A variable to store the Boolean outcome (True or False) of theany()
check.any()
: The built-in Python function for the check.iterable
: The collection (list, tuple, etc.) you want to evaluate.
Example 1: Python any()
with Basic List Check
my_list = [0, False, '', 5]
result = any(my_list)
print(result)
Code Explanation
- Line 1: Creates a list with some False-equivalent values (0, False, empty string) and one True-equivalent value (5).
- Line 2: Applies
any()
tomy_list
. Since at least one element (5) is true,result
becomes True. - Line 3: Prints the outcome (True) to the console.
Output
True
Example 2: Python any()
with String Check
my_string = " " # String with only whitespace
result = any(my_string)
print(result)
Code Explanation
- Line 1: Creates a string containing only whitespace characters.
- Line 2: Applies
any()
to the string. Even though it’s just whitespace, it’s considered non-empty, soresult
is True. - Line 3: Prints the outcome (True).
Output
True
Example 3: Python any()
with Dictionary Check (Values)
my_dict = {'a': 0, 'b': False, 'c': 'Hello'}
result = any(my_dict.values())
print(result)
Code Explanation
- Line 1: Creates a dictionary with some False-equivalent values (0, False) and one True-equivalent value (‘Hello’).
- Line 2: Applies
any()
to the dictionary’s values. ‘Hello’ is truthy, soresult
is True. - Line 3: Prints the outcome (True).
Output
True
Example 4: Python any()
with List with Condition
numbers = [1, 3, 5, 7, 9]
result = any(num % 2 == 0 for num in numbers)
print(result)
Code Explanation
- Line 1: A list of odd numbers
- Line 2: Uses a generator expression to check if any number in the list is even.
- Line 3: Prints the outcome (False, as no number is even)
Output
False