Any() and all() in Python

any()

The any() function takes iterable as a parameter: any(iterable).

Iterators can be lists, tuples or dictionaries.

If all elements in iterable are true, the any() function will return "True". However, if the Iterable passed to the function is empty, it returns "False".

This function is similar to the code block below

def any(iterable):    
for element in iterable:        
if element:          
return True    return False

The following is an example of using any to return a number greater than 3 as True. Here we use list comprehensions to keep the code simple.

recommend:

020 is continuously updated, the small circle of boutiques has new content every day, and the concentration of dry goods is extremely high.
There are everything you want to make connections and discuss technology!
Be the first to join the group and outperform your peers! (There is no fee for joining the group)
Click here to communicate and learn with Python developers.
Group number: 745895701

Free upon application:

Python software installation package, Python actual combat tutorial,
free collection of materials, including Python basic learning, advanced learning, crawling, artificial intelligence, automated operation and maintenance, automated testing, etc.

list=[2,3,4,5,6,7]
print(any([num>3 for num in list]))

The output is "True" because 4, 5, 6, and 7 are greater than 3.

all()

The all() function also takes iterable as a parameter: all(iterable) .

Only when all items in iterable are true, the all() function returns "True".

Even if one item is false, it will return "False". However, if iterable is empty, "True" is returned.

The all() function is similar to the following code block

def all(iterable):    
for element in iterable:       
if not element:          
return False    
return True

The following is an example of using any to return numbers greater than 3.

list=[1,2,3,3]
print(all([num>3 for num in list]))

The output is False because no number in the provided list is greater than 3.

In the dictionary, the all() and any() functions both check the key that returns True or False, not the key that returns the value.

Guess you like

Origin blog.csdn.net/Python_xiaobang/article/details/112392732