In chapter 2 of Data Science from Scratch by Joel Grus, the following examples are provided:
all([ ]) # True, no falsy elements in the list
any([ ]) # False, no truthy elements in the list
According to Grus, Python treats []
(an empty list) as a "falsey" argument. So why do we get different results based on whether the all()
or any()
argument is applied to an empty list?
Per the documentation of all
:
all(iterable)
Return
True
if all elements of the iterable are true (or if the iterable is empty).
And the documentation for any
:
any(iterable)
Return
True
if any element of the iterable is true. If the iterable is empty, returnFalse
.
An empty iterable []
is falsey, but it doesn't matter as the return value is just by implementation.
If you're wondering why this happens, it's just a consequence of the implementation. If you look at the equivalent code for all
from the documentation:
def all(iterable): for element in iterable: if not element: return False return True
Because of this specific implementation, if the iterable is empty, the for
loop is skipped completely as there are no elements. Thus, it returns True
. For any
, the documentation provides the equivalent code:
def any(iterable): for element in iterable: if element: return True return False
The reason it returns False
for an empty iterable is the same reason all
return True
. Since there are no elements in the list, the for
loop is skipped and it returns False
.
This implementation does have a reasoning, since empty set logic makes all
return true, see this Math.SE post and this SO answer. all
can be thought of as "there are as many true elements as elements". Since an empty set has no true elements and no elements, it returns true because 0 equals 0. any
can be thought of as "there's at least one...", and since the set is empty, there's not at least one because there is not even one element. Thus all
returns true for an empty set, and any
returns false for an empty set.
The logical reasoning behind this definition is as follows:
any
is related to the existential quantifier while all
is related to the universal quantifier and follows their logical norms.
Translate any
as there is at least one: At least one element of []
evaluates to true <-- NO.
See https://math.stackexchange.com/questions/281735/quantification-over-the-empty-set or https://math.stackexchange.com/questions/202452/why-is-predicate-all-as-in-allset-true-if-the-set-is-empty -
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With