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

后端 未结 7 1854
暗喜
暗喜 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:24

    Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can alternatively explicitly capture a witness of an any expression or a counterexample of an all expression:


    To quote a couple examples from the PEP description:

    if any(len(long_line := line) >= 100 for line in lines):
      print("Extremely long line:", long_line)
    
    if all((nonblank := line).strip() == '' for line in lines):
      print("All lines are blank")
    else:
      print("First non-blank line:", nonblank)
    

提交回复
热议问题