3

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?

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
graywarbler
  • 85
  • 1
  • 7

2 Answers2

3

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, return False.

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.

Community
  • 1
  • 1
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
3

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 -

Community
  • 1
  • 1
le_m
  • 19,302
  • 9
  • 64
  • 74