Python all() Function

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 to True, all(iterable) returns True.
  • Otherwise, if at least one item evaluates to False, it returns False.
  • It iterable is empty, it returns True.

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

Official documentation

https://docs.python.org/3/library/functions.html#all

By remaining on this website or using its content, you confirm that you have read and agree with the Terms of Use Agreement.

We are not liable for any damages resulting from using this website. Any information may be inaccurate or incomplete. See full Limitation of Liability.

Content may include affiliate links, which means we may earn commission if you buy on the linked website. See full Affiliate and Referral Disclosure.

We use cookies and similar technology to improve user experience and analyze traffic. See full Cookie Policy.

See also Privacy Policy on how we collect and handle user data.

© 2024 PyTut