Search code examples
pythonvariablesbooleanswap

How is this swap type expression working?


I have been experimenting with python. I found the swapping method for variables:

var1, var2 = var2, var3

I thought to use the same method with comparison (==), but the output is not satisfying.

>>> foo = 2
>>> bar = 3
>>> foo, bar == bar, foo
(2, True, 2)
>>> 

I thought it would give simply False. Reason:

foo is not equal to bar and bar is not equal to foo

enter image description here

I made some more tests:

>>> foo = 2
>>> bar = 3
>>> foobar = 4
>>> foo, bar, foobar == foobar, foo, bar
(2, 3, True, 2, 3)
>>> 

The result is still sort of same and I expected it to give False. Reason:

enter image description here


How is this working?


Solution

  • It has to do with operator precedence, just like

    2 + 3 * 4 == 14
    

    because it is the same as (because * has higher precedence than +)

    2 + (3 * 4) 
    

    the expression

    var1, var2 = var2, var3
    

    is the same as (because the comma-operator has higher precedence than the assignment operator):

    (var1, var2) = (var2, var3)
    

    and

    var1, var2 == var2, var3
    

    is the same as (because the == operator has higher precedence than the comma-operator)

    var1, (var2 == var2), var3
    

    The relevant part of the manual: https://docs.python.org/3/reference/expressions.html#evaluation-order

    The desired result, i.e. an expression that yields

    (a==c), (b==d)
    

    from

    a, b ... c, d
    

    is slightly more complicated in the general case. You can of course just write (a==c), (b==d) or even a==c, b==d, but @AdamSmith's suggestion will work for any number of parameters (and you don't need to extract the tuple elements):

    all(x==y for x,y in zip([a, b], [c, d]))