Home >Backend Development >Python Tutorial >Convenient usage of all() function and any() function in Python

Convenient usage of all() function and any() function in Python

不言
不言forward
2018-12-07 17:20:593603browse

What this article brings to you is about the convenient usage of all() function and any() function in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

We may face such a problem during program development?

How to judge whether all the elements in an iterable object are true? Our approach may be to traverse for..in and then judge through the bool() function. In fact, this method is feasible, but it is a bit complicated for the code. Redundant, therefore, I will introduce to you an extremely simple method

Built-in function all()

First Take a look at the source code

def all(*args, **kwargs): # real signature unknown
    """
    Return True if bool(x) is True for all values x in the iterable.
    
    If the iterable is empty, return True.
    """
    pass

Next let’s enjoy the convenience of this method

my_list=['jim','rose','','sam']
print(all(my_list)) #返回结果:False
print(all([]))#返回结果:True

Python also has a built-in function any() to determine whether there is an iterable object bool() is true element

Source code

def any(*args, **kwargs): # real signature unknown
    """
    Return True if bool(x) is True for any x in the iterable.
    
    If the iterable is empty, return False.
    """
    pass

Example test

    my_list=['jim','rose','','sam']
    print(any(my_list)) #返回结果:True
    print(any([]))#返回结果:False

Summary:

all() is false if false, any() is true if true

The above is the detailed content of Convenient usage of all() function and any() function in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete