Python any() function with Examples

Python any() function is one of the built-in functions. It takes iterable as an argument and returns True if any of the element in the iterable is True. If iterable is empty, then it returns False.

Python any() function

Python any() function is a utility method and shortcut to below function.

Let’s look at some of the examples of python any() function.

Python any() example with boolean

Output:

Python any() with empty iterable

Python any() with list of strings

Output:

When we want an object boolean value, python looks for __bool__ function in the object.

If __bool__ function is not defined, then len() function is called if it’s defined. The object boolean value is considered as True if len() output is non-zero.

If a class defines neither __len__() nor __bool__() functions, all its instances are considered True.

Python 3 uses __bool__ function to check object boolean value, if you are using python 2.x then you have to implement __nonzero__ function.

Python any() with custom objects

Let’s test above explanation with a custom class. We will create a custom Employee class and use its objects in the list and call any() function on it.

Output:

Since our Employee class doesn’t have __len__() and __bool__() function defined, it’s boolean value is True.

Let’s go ahead and define __len__() function for the Employee class as below.

Now the output of earlier code snippets will be:

Notice that len() function is getting called when any() is used with the list of Employee objects. Since the first object in the iterable returned True, other elements are not required to be evaluated for the boolean value.

Now let’s define __bool__ function for the Employee class and see what happens with the above code.

Output:

It’s clear from the output that if __bool__ function is defined, then it’s used for getting the python object boolean value.

Notice that second list any() function output is False and boolean value is retrieved for all the objects in the list.

That’s all for python any() function examples.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: