any() and all() in Python

ashwinsharmap

Ashwin Sharma P

Posted on January 7, 2021

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

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.
💖 💪 🙅 🚩
ashwinsharmap
Ashwin Sharma P

Posted on January 7, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Functions()
python Functions()

July 26, 2024

Python Basics: Functions
beginners Python Basics: Functions

May 29, 2022

Introduction to Python Functions
python Introduction to Python Functions

August 5, 2021

any() and all() in Python
python any() and all() in Python

January 7, 2021