The any() function returns True if any item in an iterable is True. Otherwise, it returns False.
Syntax
any(iterable)any() Parameters
Python any() function parameters:
| Parameter | Condition | Description |
|---|---|---|
| iterable | Required | An iterable of type (list, string, tuple, set, dictionary etc.) |
any() Return Value
Python any() function returns a boolean value:
Trueif at least one element of an iterable is trueFalseif all elements are false or if an iterable is empty
Falsy Values in Python
Falsy values are those that evaluate to False in a boolean context:
- Constants defined to be false:
NoneandFalse. - Zero of any numeric type: Integer (
0), Float (0.0), Complex (0j),Decimal(0),Fraction(0, 1). - Empty sequences and collections: Lists (
[]), Tuples (()), Dictionaries ({}), Sets (set()), Strings (""),range(0) - Any custom object for which the
__bool__()method is defined to returnFalse, or the__len__()method returns0when__bool__()is not defined.
Examples
Some examples of how to use any() function.
any() function on List
my_list = [0, 0, 0]
print(any(my_list)) # Output: False
my_list = [0, 1, 1]
print(any(my_list)) # Output: Trueoutput
False
TrueOther examples:
my_list = [False, 0, 1]
print(any(my_list)) # Output True
my_list = ('', [], 'green')
print(any(my_list)) # Output True
my_list = {0j, 3+4j, 0.0}
print(any(my_list)) # Output Trueoutput
True
True
Trueany() function on a Dictionary
The function any() can be used on dictionaries.
When you use any() function on a dictionary, it checks if any the keys of the dictionary are true (and not the values).
dict1 = {0: 'Zero', 0: 'Nil'}
print(any(dict1)) # Output: False
dict2 = {'Zero': 0, 'Nil': 0}
print(any(dict2)) # Output: Trueoutput
False
Trueany() function on Empty Iterable
The function any() can be used on iterables.
In particular, if the iterable is empty, the function returns False.
my_list = []
print(any(my_list)) # Output: False
my_list = [[], []]
print(any(my_list)) # Output: Falseoutput
False
False