The any()
function in Python returns True
if any element in the iterable passed as argument is True
. It returns False
if all elements are False
or the iterable is empty. It is used to check if at least one element in the iterable satisfies a condition.
Parameter Values
Parameter | Description |
---|---|
iterable | An iterable (list, tuple, set, etc.) of elements to check for truthiness |
Return Values
The any()
function returns bool
, either True
or False
.
How to Use any()
in Python
Example 1:
Return True
if any element of the iterable is true. If the iterable is empty, return False
.
numbers = [1, 2, 3]
result = any(num > 2 for num in numbers)
print(result) # Output: True
Example 2:
Using any()
with list comprehension to check if any string in a list has a length greater than 5.
words = ['apple', 'banana', 'pear']
result = any(len(word) > 5 for word in words)
print(result) # Output: True
Example 3:
Checking if any value in a dictionary is even using any()
.
my_dict = {'a': 1, 'b': 2, 'c': 3}
result = any(value % 2 == 0 for value in my_dict.values())
print(result) # Output: True