any()
?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 False
.
You can also check the documentation of the any()
function by using help()
, as shown below.
>>> help(any)
any()
?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 one_truth
is True
.
On the other hand, the second print statement prints False
because none of the elements are True
, i.e., all elements are False
.
all()
?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()
?Similar to any()
, 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 True
because all_true
was filled with
Passing one_true
to all()
returned False
because the list contained one or more
Finally, passing all_false
to all()
returns False
because it also contained one or more falsy values.
any()
and all()
?If you have many conditions that determine if a block of code should run, then any()
or all()
can make your code more readable.
For example, if you have a chain of or
conditions:
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 and
conditions:
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
...
Use all()
when you need to check a long series of and
conditions.
Use any()
when you need to check a long series of or
conditions.
Docs:
all()
: https://docs.python.org/3.7/library/functions.html#all
any()
: https://docs.python.org/3.7/library/functions.html#any