The Python all() method returns True if all the members in the iterable are true. In this article, you will learn about Python all() method, its syntax with examples.
Python all() method also returns True if the iterable is empty as well.
Python all() Syntax
all( iterable )
Python all() returns True only if:
- all the elements of the iterable are true
- if the iterable is empty
Note: In these functions, Python treats all the non zero values as TRUE.
You can also say that all() is like boolean AND.
If we go by the function definition, then all() is equivalent to:
def all(iterable): for element in iterable: if not element: return False return True
So what actually happens in all() function is that it iterates through the iterable and checks for a False element (e.g 0) and if it does not find any False element in the iterable, it returns True.
In an empty iterable, there is no any value to be False. Hence, it returns True for an empty iterable.
Python all() Example
Let’s take a series of examples to know how all() method works with different types of iterables.
>>> #When any one of the value is FALSE >>> all([True,True,False]) False >>> #When all elementss are TRUE >>> all([True,True,True]) True >>> #In case of empty iterable >>> all() True >>> #all() for lists >>> x = [1,2,3,4] >>> all(x) True >>> x = [1,2,0,3] >>> all(x) False >>> #all() for strings >>> str1 = "Hy Adam" >>> all(str1) True >>> str1 = "Hy 000" >>> all(str1) True
Notice that the Zero (0), when used with strings, doesn’t return False. It is because ‘0’ is not treated as FALSE, only 0 is treated as a FALSE value.