Python’s any() and all() functions

Python has two built-in functions that you can use to check if all or any of the items in an iterable meet certain criteria. These functions are called all() and any(). 

all() 

The all() function returns True if all of the items in the list are True. Otherwise, it returns False. 

Here’s a simple example: 

>>> all([True, True, True]) True 
>>> all([True, False, True]) False 

any() 

The any() function returns True if any of the items in the list are True. Otherwise, it returns False. 

Here’s a simple example: 

>>> any([True, True, True]) True 
>>> any([True, False, True]) True 
>>> any([False, False, False]) False 

You can use all() and any() to check if all or any of the items in a list meet certain criteria. 

For example, you could use them to check if all of the items in a list are positive numbers: 

>>> all([I > 0 for i in [1, 2, 3, 4, 5]]) True 

Or you could use them to check if any of the items in a list are positive numbers: 

>>> any([I > 0 for i in [1, 2, 3, 4, 5]]) True 

We’ve used lists here but the concept works on any iterable.

Previous
Previous

What is a Binary Tree and how do you create one in Python?

Next
Next

Adding validation support for JSON in Django Models