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

前端 未结 8 1291
清酒与你
清酒与你 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:51

    Alongside the other answers that mentioned the precedence of not is lower than in, actually your statement is equivalent to :

    not (True in [False, True])
    

    But note that if you don't separate your condition from the other ones, python will use 2 roles (precedence or chaining) in order to separate that, and in this case python used precedence. Also, note that if you want to separate a condition you need to put all the condition in parenthesis not just the object or value :

    (not True) in [False, True]
    

    But as mentioned, there is another modification by python on operators that is chaining:

    Based on python documentation :

    Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.

    For example the result of following statement is False:

    >>> True == False in [False, True]
    False
    

    Because python will chain the statements like following :

    (True == False) and (False in [False, True])
    

    Which exactly is False and True that is False.

    You can assume that the central object will be shared between 2 operations and other objects (False in this case).

    And note that its also true for all Comparisons, including membership tests and identity tests operations which are following operands :

    in, not in, is, is not, <, <=, >, >=, !=, ==
    

    Example :

    >>> 1 in [1,2] == True
    False
    

    Another famous example is number range :

    7

    which is equal to :

    7

提交回复
热议问题