any() Builtin Function

Python – any()

Python any() builtin function returns a boolean value of True if any of the items in the given iterable is True, else it return False.

Syntax

The syntax of any() function is

any(x)

where x is an iterable like list, tuple, etc.

Examples

Check if any of the items in list is True

In the following program, we take a list of items x where two of the items are True, and find out the output of any() with x passed as argument to it.

Python Program

x = [True, False, False, True]
output = any(x)
print(f'x      : {x}')
print(f'any(x) : {output}')
Run

Output

x      : [True, False, False, True]
any(x) : True

Now, let us change all of the items in x to False, and find out the output.

Python Program

x = [False, False, False, False]
output = any(x)
print(f'x      : {x}')
print(f'any(x) : {output}')
Run

Output

x      : [False, False, False, False]
any(x) : False

Check if any the strings are non-empty in a list

An empty string is False, and a non-empty string is True in terms of logical values. So, if we need to check if any the items in given list are non-empty strings, pass the list of strings to any() function.

Python Program

x = ["apple", "", "cherry", "", ""]
output = any(x)
print(f'x      : {x}')
print(f'any(x) : {output}')
Run

Output

x      : ['apple', '', 'cherry', '', '']
any(x) : True

Now, let us take all empty strings in the list and find out the result.

Python Program

x = ["", "", "", "", ""]
output = any(x)
print(f'x      : {x}')
print(f'any(x) : {output}')
Run

Output

x      : ['', '', '', '', '']
any(x) : False

Summary

In this tutorial of Python Examples, we learned the syntax of any() function, and how to find if any of the items in the given iterator is True using any() with examples.