Python any()
function is used to check if provided list, dictionary, etc. items are True or False. If the provided object items are all True
boolean value is returned. If the provided object all items are False the False
boolean value is returned. The any() method is a built-in method that does not require any module to load.
any() Function Syntax
The any() function has very simple syntax where it only accepts the object.
any(OBJECT)
- OBJECT is an object like list, dictionary, string, integer etc.
any() Function Return Values
The any() function returns True and False values according to the different situations.
Condition | Return Value |
---|---|
All values are True | True |
All values are not False | False |
One value is True(others are False) | True |
One value is False (others are True) | True |
Empty Iterable | False |
Check If Provided Object Is Iterable
Let’s start with a simple example where we provide a list that contains some items.
numbers = [0,1,2,3]
result = any(numbers)
# Prints True as 1,2,3 are True but 0 is False
print(result)
numbers = [0]
result = any(numbers)
# Prints False 0 is False
print(result)
numbers = ["False","False"]
result = any(numbers)
# Prints False as all items are False
print(result)
numbers = [ "False","False","True"]
result = any(numbers)
# Prints True as there is one True and two False
print(result)
Check Python List with any() Function
One of the most popular usages for the any() function is using it with the list type.
mylist= [0,1]
#Prints True as 1 is True
print(any(mylist))
mylist= [0,"False"]
#Prints False as 0 and "False" are False
print(any(mylist))
mylist= [0,"False",3]
#Prints True as 3 is True
print(any(mylist))
Check Python String with any() Function
The any() function can be used with the string type. The any() function simply checks if the provided string is empty or not. If there is a single character the any() function returns True and if not returns False.
s="pythotect"
#Prints True
print(any(s))
s="0"
#Prints True
print(any(s))
s="000"
#Prints True
print(any(s))
s="-1"
#Prints True
print(any(s))
s=""
#Prints False
print(any(s))