I am referring to the following python code
all(a==2 for a in my_list)
I expect the above code to return True if all the elements in my_list are 2. but when I make my_list empty and run it as
my_list = []
all(a==2 for a in my_list)
it returns True as well. I am confused with this behaviour. Is it not supposed to return False as there is no element in my_list with value 2?
"all" applied to an empty list is "vacuously true", as is easily confirmed:
Similarly, "if 0 = 1 then the moon is square" is true. More generally, "all P are Q" -- if there are no P's then the statement is considered true, as it can be captured formally as "For all x, if x is P then x is Q". Ultimately, these are true because the conditional logical operator (if-then) evaluates to True whenever the antecedent (the first clause) is False: "if False then True" evaluates to True. Recall that "if A then B" is equivalent to "(not A) or B".
Consider a recursive definition of
all
:If every element in
L
is true, then it must be true that both the first item inL
is true, and thatall(L[1:])
is true. This is easy to see for a list with several items, but what about a list with one item. Clearly, every item is true if the only item is true, but how does our recursive formulation work in that case? Definingall([])
to be true makes the algorithm work.Another way to look at it is that for any list
L
for whichall(L)
is not true, we should be able to identify at least one element,a
, which is not true. However, there is no sucha
inL
whenL
is empty, so we are justified in saying thatall([])
is true.The same arguments work for
any
. Ifany(L)
is true, we should be able to identify at least one element inL
that is true. But since we cannot for an empty listL
, we can say thatany([])
is false. A recursive implementation ofany
backs this up:If
L[0]
is true, we can return true without ever making the recursive call, so assumeL[0]
is false. The only way we ever reach the base case is if no element ofL
is true, so we must returnFalse
if we reach it.It's true because for every element in the list, all 0 of them, they all are equal to 2.
You can think of all being implemented as:
Whereas any is:
That is to say,
all
is innocent until proven guilty, andany
is guilty until proven innocent.