any() function in Python
Introduction
The any()
function returns True
if any element in the given iterable is true. If not, it returns False
.
The any()
function takes a single parameter iterable
and returns True
if any element in an iterable is true or False
if all elements in an iterable are false or if an iterable is empty.
The syntax of the any()
function is:
any(iterable)
where iterable can be any iterable (list, tuple, dictionary, etc.) which contains the elements.
Since any()
can return True
and False
depending upon the conditions, we can summarise its return value in the following table:
Return value of any()
in various conditions| Condition | Return Value | | --- | --- | | All values are True
| True
| | All values are False
| False
| | One of the values in True
(others are False
) | True
| | One of the values is False
(others are True
) | True
| | Empty iterable | False
|
Condition | Return Value |
All values are True | True |
All values are False | False |
One of the values in True (others are False ) | True |
One of the values is False (others are True ) | True |
Empty Iterable | False |
Working of any()
for lists, tuples, and sets
## All values are true
list1 = [1, 2, 3, 4, 5]
print(any(list1))
## All values are false
list2 = [0, False]
print(any(list2))
## One value is false(i.e. 0)
list3 = [1, 2, 3, 4, 0]
print(any(list3))
## One value is true(i.e. 1)
list4 = [0, False, 1]
print(any(list4))
## Empty iterable
list5 = []
print(any(list5))
Output:
True
False
True
True
False
Working of any()
for strings
string1 = "I am learning Python built-ins"
print(any(string1))
## 0 is False but '0' is True
string2 = '00000'
print(any(string2))
## Empty String
string3 = ''
print(any(string3))
Output:
True
True
False
Working of any()
for dictionaries
## O is False
dict1 = {0: 'False', 1: 'True'}
print(any(dict1))
## All values are true
dict2 = {1: 'True', 2: 'True'}
print(any(dict2))
## One value is False
dict3 = {1: 'True', False: 0}
print(any(dict3))
## Empty dictionary
dict4 = {}
print(any(dict4))
## 0 is False but '0' is True
dict5 = {'0': 'False'}
print(any(dict5))
Output:
True
True
True
False
True
In the case of dictionaries, if all keys (not values) are false or the dictionary is empty, any()
returns False
. If at least one key is true, any()
returns True
.
Note: 0 is considered as False and 1 is considered as True in Python. In addition to that, '0' is True whereas 0 is False.
Conclusion
In this part, we learned about the Python any()
function with the help of examples.