ItsMyCode |
The any() function in Python returns True if any element of an iterable( List , set , dictionary , tuple ) is True. If not, it returns False.
any() Syntax
The syntax of any() method is
any(iterable)
any() Parameters
The any() function takes iterable as an argument the iterable can be of type list , set , tuple , dictionary , etc.
any() Return Value
The any() method returns a boolean value.
-
Trueif one of the elements in iterable is true -
Falseif all the elements in iterable are false or if the iterable is empty
| Condition | Return Value |
|---|---|
| All elements are true | True |
| All elements are false | False |
| One element is true and others are false) | True |
| One element is false and others are true | True |
| Empty Iterable | False |
Example 1 – Using any() function on Python Lists
# All the elements in the list are true
list = [1,3,5,7]
print(any(list))
# All the elements in the list are false
list = [0,0,False]
print(any(list))
# Some of the elements are false
list = [1,5,7,False]
print(any(list))
# Only 1 element is true
list = [0, False, 5]
print(any(list))
# False since its Empty iterable
list = []
print(any(list))
Output
True
False
True
True
False
Example 2 – Using any() function on Python Strings
# Non Empty string returns True
string = "Hello World"
print(any(string))
# 0 is False but the string character of 0 is True
string = '000'
print(any(string))
# False since empty string and not iterable
string = ''
print(any(string))
Output
True
True
False
Example 3 – Using any() function on Python Dictionaries
In the case of a dictionary, only if all the keys( not values ) of the dictionary are either false or if the dictionary is empty, the any() method returns False. If at least one key is true, then any() returns True.
# All elements in dictionary are true
dict = {1: 'Hello', 2: 'World'}
print(any(dict))
# All elements in dictionary are false
dict = {0: 'Hello', False: 'World'}
print(any(dict))
# Some elements in dictionary are true and rest are false
dict = {0: 'Hello', 1: 'World', False: 'Welcome'}
print(any(dict))
# Empty Dictionary returns false
dict = {}
print(any(dict))
Output
True
False
True
False
Example 4 – Using any() function on Python Tuples
# All elements of tuple are true
t = (1, 2, 3, 4)
print(any(t))
# All elements of tuple are false
t = (0, False, False)
print(any(t))
# Some elements of tuple are true while others are false
t = (5, 0, 3, 1, False)
print(any(t))
# Empty tuple returns false
t = ()
print(any(t))
Output
True
False
True
False
Example 5 – Using any() function on Python Sets
# All elements of set are true
s = {1, 2, 3, 4}
print(any(s))
# All elements of set are false
s = {0, 0, False}
print(any(s))
# Some elements of set are true while others are false
s = {1, 2, 3, 0, False}
print(any(s))
# Empty set returns false
s = {}
print(any(s))
Output
True
False
True
False
The post Python any() appeared first on ItsMyCode.
Top comments (0)