Search code examples
pythonboolean-expression

Why is `(True, True, True) == True, True, True` not True in Python?


Code snippet 1:

a = True, True, True
b = (True, True, True)

print(a == b)

returns True.

Code snippet 2:

(True, True, True) == True, True, True

returns (False, True, True).


Solution

  • Operator precedence. You're actually checking equality between (True, True, True) and True in your second code snippet, and then building a tuple with that result as the first item.

    Recall that in Python by specifying a comma-separated "list" of items without any brackets, it returns a tuple:

    >>> a = True, True, True
    >>> print(type(a))
    <class 'tuple'>
    >>> print(a)
    (True, True, True)
    

    Code snippet 2 is no exception here. You're attempting to build a tuple using the same syntax, it just so happens that the first element is (True, True, True) == True, the second element is True, and the third element is True.

    So code snippet 2 is equivalent to:

    (((True, True, True) == True), True, True)

    And since (True, True, True) == True is False (you're comparing a tuple of three objects to a boolean here), the first element becomes False.