Python any() Function

The any() function in Python returns True if any element of an iterable is True. For example:

x = [12, 53, True, "codes"]
print(any(x))

x = [False, False, True, False]
print(any(x))

x = [True, True, True]
print(any(x))

x = [12, 32, 54, False]
print(any(x))

x = [False, False, False]
print(any(x))

x = []
print(any(x))

The output produced by this Python program, demonstrating the any() function is given below:

True
True
True
True
False
False

Python any() Function Syntax

The syntax of any() function in Python is:

any(iterable)

Note - The any() function always returns a boolean value. That is, it returns either True or False.

Note - The any() returns True if any element is True. Otherwise returns False if the iterable is empty or the iterable contains 0 or/and False as its all elements.

Python any() Function Example

Here is a simple example program on any() function. This program uses list as an iterable to demonstrate the any function in Python:

x = [0]
print(any(x))

x = [False]
print(any(x))

x = [False, 0]
print(any(x))

x = []
print(any(x))

x = [False, 0, 10]
print(any(x))

x = [False, 0, True]
print(any(x))

Here is its output:

False
False
False
False
True
True

Note - The any() function works in similar way for tuple, set, and dictionary.

Note - In case of dictionary, the any() function consider the key. Here is an example:

x = {0: False, 1: False}
print(any(x))

d = {0: False, False: True}
print(any(d))

d = {}
print(any(d))

d = {"False": "0", "False": "1"}
print(any(d))

Following is its output:

True
False
False
True

Note - Enclosing the False inside a double quote, meaning the False gets considered as a string. Therefore "False" as key gets considered as a key with some string.

Note - Either if the dictionary is empty, or if all the key of dictionary is 0 or False, then only the any() function returns False. Otherwise, it returns True, if any key is True.

The any() function can also be used with strings. Here is an example:

x = "False"
print(any(x))

x = "codescracker"
print(any(x))

x = ""
print(any(x))

The output is:

True
True
False

Python Online Test


« Previous Function Next Function »



Like/Share Us on Facebook 😋