5

What is the associativity of comparison operators in Python? It is straightforward for three comparisons, but for more than that, I'm not sure how it does it. They don't seem to be right- or left-associative.

For example:

>>> 7410 >= 8690 <= -4538 < 9319 > -7092        
False    
>>> (((7410 >= 8690) <= -4538) < 9319) > -7092 
True

So, not left-associative.

>>> 81037572 > -2025 < -4722 < 6493           
False
>>> (81037572 > (-2025 < (-4722 < 6493)))     
True

So it's not right-associative either.

I have seen some places that they are 'chained', but how does that work with four or more comparisons?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
John Doe
  • 51
  • 2

3 Answers3

7

Chained comparisons are expanded with and, so:

a <= b <= c

becomes:

a <= b and b <= c

(b is only evaluated once, though). This is explained in the language reference on comparisons.

Note that lazy evaluation means that if a > b, the result is False and b is never compared to c.

Your versions with parentheses are completely different; a <= (b <= c) will evaluate b <= c then compare a to the result of that, and isn't involved at all, so it's not meaningful to compare the results to determine associativity.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
1

python short-circits boolean tests from left to right:

7410>=8690<=-4538<9319>-7092        -> False

7410>=8690 is False. that's it. the rest of the tests is not preformed.

note that

True == 1
False == 0

are both True and apply when you compare the booleans with integers. so when you surround the statement with brackets you force python to do all the tests; in detail:

(((7410>=8690)<=-4538)<9319)>-7092
      False   <=-4538
            False     <9319
                    True  >-7092
                         True
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
-1

You are making an error with types, when you write 81037572>-2025 then the system thinks of this as True or False and associates it with 1 and 0. It therefore then gives you a comparison with those binary numbers.

Cedric
  • 117
  • 1
  • 12
  • I realise that they return boolean values. Python uses the boolean values as integers during a comparison. So, for example, 1<2<3<4<5, gives a true result and 1>2>3>4>5 returns false. I know that it will not return the mathematically correct result. They were just examples, I'm just asking how exactly they are interpreted. In what order. – John Doe Sep 12 '15 at 07:26
  • From what I can tell it is right to left. Since `0 < 3 < 2`returns `False` – Cedric Sep 12 '15 at 07:32
  • If that was the case, then 0<=1>2 would be true. – John Doe Sep 12 '15 at 07:49
  • `0 <= 1 > 2` is evaluated as `0 <= 1 and 1 > 2` --> `True and False` --> `False` – jonrsharpe Sep 12 '15 at 10:18