Python any() Method

The Python any() method returns True if any member in the iterable is true. In this article, you will learn about Python any() method, its syntax with examples.

Unlike all() method, any() returns False if the iterable is empty.

python any()

Python any() Syntax

any( iterable )

any() takes an iterable as input and checks that all of the values evaluate to True.  The iterable is a sequence of elements (liststuplesdictionarysets etc).

Note: In these functions, Python treats all the non zero values as TRUE.

How exactly does Python any() method works?

all() method is like boolean OR.

If we go by function definition, then the any() method is equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

So what actually happens in any() function is that it iterates through the iterable and checks for a True element (e.g any value > 0) and if it does not find any True element in the iterable, it returns False and if it finds any True value it will return True.

Python any() Example

Let’s take an example and see how Python any() method works with lists, tuples, strings, dictionaries and others.

>>> #When any one of the value is TRUE
>>> any([True,False,False])
>>> #When all elementss are TRUE
>>> any([True,True,True])

>>> #In case of empty iterable
>>> any([])

>>> #any() for lists
>>> x = [1,2,3,4]
>>> any(x)
>>> x = [1,0,0,0]
>>> any(x)
>>> x = [0,0,0,0]

>>> #any() for strings
>>> str1 = "Hola amigo"
>>> any(str1)

>>> #any() for dictionary
>>> x = [0:'Python'] 
>>> any(x)
>>> x = [0:'Python',1:'Programming']
>>> any(x)