How does all() in python work on empty lists

前端 未结 4 1191
忘掉有多难
忘掉有多难 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:48

    Consider a recursive definition of all:

    def all(L):
        if L:
            return L[0] and all(L[1:])
        else:
            ???
    

    If every element in L is true, then it must be true that both the first item in L is true, and that all(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? Defining all([]) to be true makes the algorithm work.

    Another way to look at it is that for any list L for which all(L) is not true, we should be able to identify at least one element, a, which is not true. However, there is no such a in L when L is empty, so we are justified in saying that all([]) is true.

    The same arguments work for any. If any(L) is true, we should be able to identify at least one element in L that is true. But since we cannot for an empty list L, we can say that any([]) is false. A recursive implementation of any backs this up:

    def any(L):
        if L:
            return L[0] or any(L[1:])
        else:
            return False
    

    If L[0] is true, we can return true without ever making the recursive call, so assume L[0] is false. The only way we ever reach the base case is if no element of L is true, so we must return False if we reach it.

提交回复
热议问题