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