Why does “not(True) in [False, True]” return False?

前端 未结 8 1273
清酒与你
清酒与你 2020-12-04 05:29

If I do this:

>>> False in [False, True]
True

That returns True. Simply because False is in the list.

8条回答
  •  自闭症患者
    2020-12-04 05:54

    To clarify on some of the other answers, adding parentheses after a unary operator does not change its precedence. not(True) does not make not bind more tightly to True. It's just a redundant set of parentheses around True. It's much the same as (True) in [True, False]. The parentheses don't do anything. If you want the binding to be more tight, you have to put the parentheses around the whole expression, meaning both the operator and the operand, i.e., (not True) in [True, False].

    To see this another way, consider

    >>> -2**2
    -4
    

    ** binds more tightly than -, which is why you get the negative of two squared, not the square of negative two (which would be positive four).

    What if you did want the square of negative two? Obviously, you'd add parentheses:

    >>> (-2)**2
    4
    

    However, it's not reasonable to expect the following to give 4

    >>> -(2)**2
    -4
    

    because -(2) is the same as -2. The parentheses do absolutely nothing. not(True) is exactly the same.

提交回复
热议问题