Contents
Python – any()
Python any() builtin function is used check if there is at least one item that is True in the given iterable.
any() returns a boolean value of True if any of the items in the given iterable is True, else it return False.
In this tutorial, you will learn the syntax of any() function, and then its usage with the help of example programs.
Syntax
The syntax of any() function is
any(x)
where
Parameter | Description |
---|---|
x | An iterable like list, tuple, etc. |
Examples
1. 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 Code CopyOutput
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 Code CopyOutput
x : [False, False, False, False]
any(x) : False
2. Check if any of 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 Code CopyOutput
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 Code CopyOutput
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.