Python any() Function

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 iterable is True, any() returns True.
  • If all items evaluate to False, it returns False.
  • If the input iterable is empty, any() returns False.

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

Official documentation

https://docs.python.org/3/library/functions.html#any

By remaining on this website or using its content, you confirm that you have read and agree with the Terms of Use Agreement.

We are not liable for any damages resulting from using this website. Any information may be inaccurate or incomplete. See full Limitation of Liability.

Content may include affiliate links, which means we may earn commission if you buy on the linked website. See full Affiliate and Referral Disclosure.

We use cookies and similar technology to improve user experience and analyze traffic. See full Cookie Policy.

See also Privacy Policy on how we collect and handle user data.

© 2024 PyTut