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

前端 未结 8 1221
清酒与你
清酒与你 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.

    0 讨论(0)
  • 2020-12-04 05:57

    Operator precedence 2.x, 3.x. The precedence of not is lower than that of in. So it is equivalent to:

    >>> not ((True) in [False, True])
    False
    

    This is what you want:

    >>> (not True) in [False, True]
    True
    

    As @Ben points out: It's recommended to never write not(True), prefer not True. The former makes it look like a function call, while not is an operator, not a function.

    0 讨论(0)
提交回复
热议问题