Python any() function takes a sequence as input (such as a tuple or list) and checks if at least one item is True.
- If at least one item in the input
iterableisTrue,any()returnsTrue. - If all items evaluate to
False, it returnsFalse. - If the input
iterableis empty,any()returnsFalse.
Therefore, any() is the equivalent of:
def any(iterable):
for i in iterable:
if i:
return True
return False
It is similar to the function all(), which checks if all the items are True.
Examples
>>> any([1, 2, 3]) True >>> any([1, 0, 0]) True >>> any([0, 0, 0]) False >>> any([]) False
Input data types
The argument to any() can be any iterable type, including list, tuple, set, or dict.
any() with dict
In a dict, any() evaluates keys, not values. If at least one key is True, any() returns True. Empty dict returns False.
>>> any({1 : 1, 0 : 2})
True
>>> any({0 : 1, '' : 2})
False
any() with str
any() also works with strings, as they are iterable. It returns True, unless the string is empty – then it returns False.
>>> any('PyTut')
True
>>> any('Python Tutorials')
True
>>> any('0')
True
>>> any('')
False
any() does not work with int, float, bool
Data types which are not iterable, such as int and float, do not work as arguments to any(). Even the booleans True, False.
>>> any(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable >>> any(1.1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'float' object is not iterable >>> any(True) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'bool' object is not iterable