How does all() in python work on empty lists

前端 未结 4 1189
忘掉有多难
忘掉有多难 2020-12-14 19:51

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_li

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 20:36

    "all" applied to an empty list is "vacuously true", as is easily confirmed:

    >>> all([])
    True
    

    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".

提交回复
热议问题