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

后端 未结 7 1862
暗喜
暗喜 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:14

    This very issue came up up on the Python developer's mailing list in 2005, when Guido Van Rossum proposed adding any and all to Python 2.5.

    Bill Janssen requested that they be implemented as

    def any(S):
        for x in S:
            if x:
                return x
        return S[-1]
    
    def all(S):
        for x in S:
            if not x:
                return x
        return S[-1]
    

    Raymond Hettinger, who implemented any and all, responded specifically addressing why any and all don't act like and and or:

    Over time, I've gotten feedback about these and other itertools recipes. No one has objected to the True/False return values in those recipes or in Guido's version.

    Guido's version matches the normal expectation of any/all being a predicate. Also, it avoids the kind of errors/confusion that people currently experience with Python's unique implementation of "and" and "or".

    Returning the last element is not evil; it's just weird, unexpected, and non-obvious. Resist the urge to get tricky with this one.

    The mailing list largely concurred, leaving the implementation as you see it today.

提交回复
热议问题