The built-in Python function all()
checks if all items in a sequence (such as a list
, tuple
, or set
) are True
.
It takes one input iterable
.
- If all items in
iterable
evaluate toTrue
,all(iterable)
returnsTrue
. - Otherwise, if at least one item evaluates to
False
, it returnsFalse
. - It
iterable
is empty, it returnsTrue
.
Therefore, all()
is the equivalent of:
def all(iterable):
for i in iterable:
if not i:
return False
return True
It is similar to the function any()
, which checks if any of the items are True
.
Examples
>>> all([1, 2, 3]) True >>> all([1, 0, 1]) False >>> all([]) True >>> all({1, 2, 2, 3}) True
Input data types
The argument to all()
can be any iterable type, including list
, tuple
, or set
.
all() with dict
all()
also works with dict
. It evaluates the keys, not the values. If at least one key is False
, all()
returns False
.
>>> all({1 : 0, 2 : 1}) True >>> all({0 : 1, 1 : 2}) False
all() with str
Strings are iterable, so str
also works as argument to all()
. It returns True
even if the string contains spaces or the number zero.
>>> all('Hello') True >>> all('Hello world') True >>> all('0') True >>> all('') True >>> all('False') True
all() does not work with int, float, bool
Data types which are not iterable, such as int
and float
, do not work as arguments to all()
. Even the booleans True
, False
.
>>> all(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable >>> all(1.1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'float' object is not iterable >>> all(True) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'bool' object is not iterable