Ashwin Sharma P

Sign in

any() and all() in Python

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

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.

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

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

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.

Connect on LinkedIn through www.linkedin.com/in/ashwinsharmap