How does all() in python work on empty lists

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

    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:

    def all(list, condition):
      for a in list:
        if not condition(a):
          return false
      return true
    

    Whereas any is:

    def any(list, condition):
      for a in list:
        if condition(a):
          return true
      return false
    

    That is to say, all is innocent until proven guilty, and any is guilty until proven innocent.

提交回复
热议问题