any() and all() in Python

Subscribe to my newsletter and never miss my upcoming articles

In this post, we will be looking into any() and all() functions in Python. First, let us discuss the any() function.

πŸ‘‰ any()

The any() function takes an iterable as an argument : any(iterable) .

The iterable can be a list, tuple or dictionary.

The any() function returns 'True' if any element in the iterable is true. However, it returns 'False' if the iterable passed to the function is empty.

This function is similar to the code block below

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

Below is an example of using any for returning 'True' for numbers greater than 3. Here we have used list comprehension to keep the code simple.

list=[2,3,4,5,6,7]
print(any([num>3 for num in list]))

The output is 'True' as 4,5,6 and 7 are greater than 3.

Next, we look into the all() function.

πŸ‘‰ all()

The all() function also takes an iterable as an argument: all(iterable) .

all() function returns 'True' only if all the items in the iterable are true.

Even if one item is false, it returns 'False'. However, if the iterable is empty, it returns 'True'.

all() function is similar to the code block below

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

Below is an example of using any for returning True for numbers greater than 3.

list=[1,2,3,3]
print(all([num>3 for num in list]))

The output is False as no number is greater than 3 in the provided list.

  • In dictionaries, both all() and any() functions to check the key for returning True or False and not the values.
vaibhav kumar's photo

Thanks for sharing! Learned two new functions

Ashwin Sharma P's photo

Glad you learnt something newπŸ˜ƒ

Luiz Filipe da Silva's photo

I didn't know these functions. Thanks for sharing!

Ashwin Sharma P's photo

Happy that you found it helpful. πŸ˜ƒπŸ˜Š

Kritika Singhal's photo

Very well drafted πŸ™Œ Wasn't aware about all(). Glad to learn about it.

Ashwin Sharma P's photo

Thank you😊