Why does python `any` return a bool instead of the value?

后端 未结 7 1822
暗喜
暗喜 2020-12-08 18:28

and and or return the last element they evaluated, but why doesn\'t Python\'s built-in function any?

I mean it\'s pretty easy

7条回答
  •  粉色の甜心
    2020-12-08 19:19

    It's not immediately obvious that any's value could be either False or one of the values in the input. Also, most uses would look like

    tmp = any(iterable)
    if tmp:
       tmp.doSomething()
    else:
       raise ValueError('Did not find anything')
    

    That's Look Before You Leap and therefore unpythonic. Compare to:

    next(i for i in iterable if i).doSomething()
    # raises StopIteration if no value is true
    

    The behavior of and and or was historically useful as a drop-in for the then-unavailable conditional expression.

提交回复
热议问题