How and when to use any() and all() in Python

What is any()?

any() is a function that takes in an iterable (such as a list, tuple, set, etc.) and returns True if any of the elements evaluate to True, but it returns False if all elements evaluate to False.

You can also check the documentation of the any() function by using help(), as shown below.

>>> help(any)

How do I use any()?

Passing an iterable to any() to check if any of the elements are True is as easy as:

one_truth = [True, False, False]
three_lies = [0, '', None]
print(any(one_truth))
print(any(three_lies))

The first print statement prints True because one of the elements in one_truth is True.

On the other hand, the second print statement prints False because none of the elements are True, i.e., all elements are False.


What is all()?

all() is another Python function that takes in an iterable and returns True if all of the elements evaluate to True, but that returns False if otherwise.

How do I use all()?

Similar to any(), all() takes in a list, tuple, set, or any iterable, ​like so:

all_true = [True, 1, 'a', object()]
one_true = [True, False, False, 0]
all_false = [None, '', False, 0]
print(all(all_true))
print(all(one_true))
print(all(all_false))

The first function call returned True because all_true was filled with truthyA value that evaluates to True values.

Passing one_true to all() returned False because the list contained one or more falsya value that evaluates to False values.

Finally, passing all_false to all() returns False because it also contained one or more falsy values.


When should I use any() and all()?

If you have many conditions that determine if a block of code should run, then any() or all() can make your code more readable.

For example, if you have a chain of or conditions:

if condition1 or condition2 or condition3 or condition4:
    # Do something here
    ...

You can use any() like so:

conditions = (
    condition1,
    condition2,
    condition3,
    condition4
)
if any(conditions):
    # Do something here
    ...

Similarly, if you have a long chain of and conditions:

if condition1 and condition2 and condition3 and condition4:
    # Do something here
    ...

You can use all() to make it more readable:

conditions = (
    condition1,
    condition2,
    condition3,
    condition4
)
if all(conditions):
    # Do something here
    ...

TL;DR

Use all() when you need to check a long series of and conditions.

Use any() when you need to check a long series of or conditions.


Docs:
all(): https://docs.python.org/3.7/library/functions.html#all

any(): https://docs.python.org/3.7/library/functions.html#any

Free Resources