DEV Community

loading...
Cover image for any() and all() in Python

any() and all() in Python

Ashwin Sharma P
An AI explorer and tech writer || Machine Learning || Programmer
Originally published at ashwinsharma.tech ・2 min read

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  
Enter fullscreen mode Exit fullscreen mode

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]))
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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]))
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (0)