Search code examples
pythonpython-3.xcomparison-operators

Confusing comparison output


I am confused about the following:

>>> 1,2 == 1,2
(1, False, 2)

The == operator should return only a bool (or at least I thought so). I would have expected to have, (True, True) assuming that the line would have been processed like a,b = 1,2 but performing comparison instead of assignment. Or, to have an error. But definitely not (1, False, 2).

Can anyone explain what is going on here?


Solution

  • This:

    1,2 == 1,2 
    

    is evaluated as a three element tuple that contains 1, 2 == 1 and 2 respectively. You need to use a couple of parentheses here:

    (1, 2) == (1, 2)
    

    This is stated in the Language Reference:

    Except when part of a list or set display, an expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.