any() Builtin Function

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

ParameterDescription
xAn 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 Copy

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 Code Copy

Output

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 Copy

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 Code Copy

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.

Frequently Asked Questions

1. What does any() function do in Python?

Answer:

any() function takes an iterable as argument and returns True, if there is at least one element in the iterable that evaluates to True. The function returns False, if none of the elements in the given iterable is True.

any([True, True, False]) #returns True
any([False, False, False]) #returns False
2. What is the difference between all() and any() functions in Python?

Answer:

all() function returns True, only if all the elements in the given iterable evaluate to True. Whereas any() function returns True if there is at least one element that is True in the given iterable.

abs(-8)

Related Tutorials

Code copied to clipboard successfully 👍