The Python all() function can be used to determine if all elements of an iterable are True. If any element is False, it returns False.
all() on Python lists
Example 1:
list1 = [False, True, False]
print(all(list1))
In this example False is returned, because at least one of the booleans in the list is False.
False
Example 2:
list2 = [0, 1, 2, 3]
print(all(list2))
In this example False is returned, because 1, 2, 3 are True, while 0 is False.
False
Example 3:
list3 = []
print(all(list3))
In this example True is returned, because the list is empty.
False
Example 4:
list4 = [0, False, '']
print(all(list4))
In this example False is returned, because all items in the list are False.
all() on Python strings
Example 1:
string1 = 'example string'
print(all(string1))
In this example True is returned, because the string is True.
True
Example 2:
string2 = '0'
print(all(string2))
In this example True is returned, because the string '0' is True.
The string '0' is different than the integer 0, which is False.
True
Example 3:
string3 = ''
print(all(string3))
In this example True is returned, because the empty string is True.
True
all() on Python dictionaries
If the all() function is used on a Python dictionary, it will return True if all keys are True or the dictionary is empty. If any key is False, False is returned. It is important to understand, that the keys matter, not the values of the dictionary.
Example 1:
dictionary1 = {0: 'hello'}
print(all(dictionary1))
In this example False is returned, because the key 0 is False.
False
Example 2:
dictionary2 = {}
print(all(dictionary2))
In this example True is returned, because the dictionary is empty.
True
Example 3:
dictionary3 = {0: 'hello', False: 'world'}
print(all(dictionary3))
In this example False is returned, because both keys 0 and False are False.
False
Example 4:
dictionary4 = {'0': 'hello'}
print(all(dictionary4))
In this example True is returned, because the key '0' is a string and True.
True
all() syntax
The syntax of the all function is:
all(iterable)
all() arguments
The all() function takes exactly one iterable (list, string, dictionary) as argument.
In case more or less than one iterable is given, an TypeError occurs.
all() return value
The all() function returns a boolean value:
True, if all elements are True
True, if the iterable is empty
False, if at least one of the elements is False
condition |
return value |
All values are True |
True |
One value is True, others are False |
False |
One value is False, others are True |
False |
All values are False |
False |
The iterable is empty |
True |
To check if any value is True or False, the
any() function is useful.