Home    /    Answers    /    Python
Why do we need any() function in python?

Boolean statements and conditional statements are commonly used in Python programming. Every element in an iterable is evaluated to determine its truth value.

What is the use of the built-in "any()" function in Python?

In simple words, Python's any() function returns True if any element of a given iterable (List, Dictionary, Tuple, Set, etc) is true, otherwise, it returns False.

Code

# A tuple
test_tuple = (1,False,2) 

# Use of any with tuple
print(any(test_tuple))

# A list
test_list = [0,False]

# Use of any with List
print(any(test_list))

Output

True
False

Note: When any true element is found by the Python any() function, it stops iterations

Explanation:

As shown in the first example, any() returns True because at least one element in the list is True and it is in the form of a tuple.

Due to the initial state of the list is either zero or false, any() returns False, however, the presence of a non-zero value will change the output to True.

Recommended for you