All() and Any() Functions in Python With Examples

all() and any() are convenient functions for checking the truth of the elements of lists, dictionaries, sets, generator expressions, etc.

Table of Contents

all() Function in Python


How the all() function works:

>>> help(all)
Help on built-in function all in module builtins:

all(iterable, /)
    Return True if bool(x) is True for all values x in the iterable.    
    If the iterable is empty, return True.

The logic of this function can be represented by the following example:

def is_all_true(iterable):
    for element in iterable:
        if not element:
            return False
    return True

Examples.

All values are True.
>>> all([True, True])
True
>>> all([1, 2])
True
All values are False.
>>> all([False, False])
False
>>> all([None, {}])
False
Values include both True and False.
>>> all([True, False])
False
>>> this_dict = {"a": 1, "b": 0}
>>> all(this_dict.values())
False
Empty iterable.
>>> all([])
True

any() Function in Python


How the any() function works:

>>> help(any)
Help on built-in function any in module builtins:

any(iterable, /)
    Return True if bool(x) is True for any x in the iterable.    
    If the iterable is empty, return False.

The logic of this function can be represented by the following example:

def is_any_true(iterable):
    for element in iterable:
        if element:
            return True
    return False

Examples

All values are True.
>>> any([True, True])
True
>>> any([0.1, 0.2])
True
All values are False.
>>> any([False, False])
False
>>> any([0, 0.0])
False
Values include both True and False.
>>> any([True, False])
True
>>> this_tuple = ("not an empty string", "")
>>> any(this_tuple)
True
Empty iterable.
>>> any([])
False

More Complex Examples


Combined With Other Functions, Generators and Custom Conditions

check if the elements of a list are of a specific type

>>> values = ["a", 1, "b"]
>>> all(isinstance(x, str) for x in values)
False

check if all the values in the list are greater than or equal to a certain number

>>> all(x >= 1 for x in [-1, 0, 1, 2, 3])
False

check if any value in the list is less than or equal to a certain number

>>> any(x <= 0 for x in [-1, 0, 1, 2, 3])
True

check for values starting with a specific letter

>>> all(x.startswith("a") for x in ["a", "b"])
False
>>> any(x.startswith("a") for x in ["a", "b"])
True

check if all values in the list are even; check if any value in the list are odd

 
>>> all(x%2 == 0 for x in [2, 4, 6])
True
>>> any(x%2 == 1 for x in [2, 4, 6])
False

Using all() Instead of a Chain of "and" Conditions

You can replace the following code
if condition1 and condition2 and condition3...:
    # do something
with all() function
conditions = (condition1, condition2, condition3, ...)
if all(conditions):
    # do something
Example:
user = {"name": "John", "active": True, "subscribed": True}
# both values are boolean anyway
conditions = (user["active"], user["subscribed"])
if all(conditions):
    # do something

Using any() Instead of a Chain of "or" Conditions

You can replace the following code
if condition1 or condition2 or condition3...:
    # do something
with any() function
conditions = (condition1, condition2, condition3, ...)
if any(conditions):
    # do something
Example:
product = {"name": "A", "price": 10, "in_stock": True}
conditions = (
    product["price"] == 0,
    not product["in_stock"]
    )
if any(conditions):
    # do something

Advantages of These Functions


Reliability

Built-in functions are a secure and time-tested solution.

Efficiency

all() stops iterating over the elements at the first False value.
any() stops iterating over the elements at the first True value.

Less code

You can replace a loop that just iterates over elements with these built-in functions.

Popular posts from this blog