any() is a function that takes in an iterable (such as a list, tuple, set, etc.) and returns
True if any of the elements evaluate to
True, but it returns
False if all elements evaluate to
You can also check the documentation of the
any() function by using
help(), as shown below.
Passing an iterable to
any() to check if any of the elements are
True is as easy as:
one_truth = [True, False, False] three_lies = [0, '', None] print(any(one_truth)) print(any(three_lies))
The first print statement prints
True because one of the elements in
On the other hand, the second print statement prints
False because none of the elements are
True, i.e., all elements are
all() is another Python function that takes in an iterable and returns
True if all of the elements evaluate to
True, but that returns
False if otherwise.
all() takes in a list, tuple, set, or any iterable, like so:
all_true = [True, 1, 'a', object()] one_true = [True, False, False, 0] all_false = [None, '', False, 0] print(all(all_true)) print(all(one_true)) print(all(all_false))
The first function call returned
all_true was filled with
False because the list contained one or more
False because it also contained one or more falsy values.
If you have many conditions that determine if a block of code should run, then
all() can make your code more readable.
For example, if you have a chain of
if condition1 or condition2 or condition3 or condition4: # Do something here ...
You can use
any() like so:
conditions = ( condition1, condition2, condition3, condition4 ) if any(conditions): # Do something here ...
Similarly, if you have a long chain of
if condition1 and condition2 and condition3 and condition4: # Do something here ...
You can use
all() to make it more readable:
conditions = ( condition1, condition2, condition3, condition4 ) if all(conditions): # Do something here ...
all() when you need to check a long series of
any() when you need to check a long series of
View all Courses