Python any() Function



The Python any() function is a built-in function that returns True if any of the elements of a given iterable, such as a list, tuple, set, or dictionary is truthy, otherwise, it returns False. However, if the iterable object is empty, the any() function will return False.

An iterable is an object that enables us to access its items by iterating over them. In Python, the Truthy values include non-empty strings, non-zero numbers, and non-empty iterables. On the other hand, Falsy values consist of empty iterables and strings, the number 0, and the special value None.

Syntax

Following is the syntax of the Python any() function −

any(iterable)

Parameters

The Python any() function accepts a single parameter −

  • iterable − This parameter indicates an iterable object such as a list, tuple, dictionary, or set.

Return Value

The Python any() function returns a Boolean value.

Examples

Let's understand how any() function works with the help of some examples −

Example 1

The following example shows the usage of Python any() function. Here we are creating a list named 'numerics' and applying any() function to check if the given list contains any truthy value or not.

numerics = [71, 87, 44, 34, 15]
output = any(numerics)
print("The output after evaluation:", output)

When we run above program, it produces following result −

The output after evaluation: True

Example 2

In the code below, we have a tuple of four elements and the any() function checks if any element of the tuple is truthy. Since all four elements are falsy values, this function will return False.

falsy_tup = (False, None, "", 0.0)
output = any(falsy_tup)
print("The output after evaluation:", output)

Following is an output of the above code −

The output after evaluation: False

Example 3

The code below shows how to verify if there is any common element exists between two given sets with the help of any() function.

set1 = {11, 33, 34}
set2 = {44, 15, 26}
output = any(x in set2 for x in set1)
print("Both sets have common elements:", output) 

set1 = {11, 21, 31}
set2 = {31, 41, 51}
output = any(x in set2 for x in set1)
print("Both sets have common elements:", output)

Output of the above code is as follows −

Both sets have common elements: False
Both sets have common elements: True

Example 4

In the following code, we are using any() function to check if there is any number greater than zero in the given list.

numeric_lst = [-15, -22, -54, -41, -11]
output = any(i > 0 for i in numeric_lst)
print("The list contains truthy value:", output) 

numeric_lst = [-15, -42, -23, -41, 11]
output = any(i > 0 for i in numeric_lst)
print("The list contains truthy value:", output)  

Following is an output of the above code −

The list contains truthy value: False
The list contains truthy value: True
python_built_in_functions.htm
Advertisements