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

不言
Release: 2018-12-07 17:20:59
forward
3618 people have browsed it

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
Copy after login

Next let’s enjoy the convenience of this method

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

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
Copy after login

Example test

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

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template