Python Programming
Logical Operators
Boolean Expressions
Python Lists
Code Explanation

Why does notTrue in False, True return False?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Python, expressions and their expected outputs can sometimes be counterintuitive to those new to the language or programming in general. A particularly interesting example is the expression not(True) in [False, True] . Unexpectedly, it returns False . Understanding why this happens requires a dive into operator precedence and logical evaluation in Python.

Understanding Operator Precedence

Operator precedence determines the order in which operators are evaluated. In Python, just like in many other languages, some operations are performed before others unless overridden by parentheses. Below is a simplified list of common operators sorted by their precedence, from highest to lowest:

  1. Parentheses ()
  2. Exponentiation **
  3. Unary operations like not , + , -
  4. Multiplicative operators like * , / , %
  5. Additive operators like + , -
  6. Relational operators like == , != , > , <
  7. Logical AND and
  8. Logical OR or
  9. Membership tests in , not in

From this table, it is clear that the not operator has higher precedence than the in operator.

Step-By-Step Evaluation of not(True) in [False, True]

Now, let's break down the evaluation of not(True) in [False, True] :

  1. Apply not to True :
    The not operator negates the Boolean True , transforming it to False .
    Intermediate result: False in [False, True]
  2. Evaluate Membership Test in :
    The expression now checks if the result of not True , which is False , exists in the list [False, True] . Since False is indeed present in the list, the evaluation returns True .

The reason the original expression returns False is because many assume not negates the entire expression following it due to the lack of parentheses, which it doesn't. not here only negates the operand immediately after it, i.e., True , and not the result of the entire membership test True in [False, True] .

Correct Usage with Parentheses

If the intention is to negate the entire membership expression, parentheses must be used to adjust the precedence:

  • **not True vs not (True) **: Both return False as not directly applies to True .
  • **False in [False, True] **: Direct membership test, returns True .
  • **True not in [False, True] **: True is in the list, but the not in changes the context, returning False .

Course illustration
Course illustration

All Rights Reserved.