1

Running this in the REPL gives me

>>> 1 == 2 == 2
False

Which surprised me, in C this would evaluate to 1. I expected the right-hand side to evaluate to True and 1 == True is True in Python. For example, this evaluates as I would expect:

>>> 1 == (2 == 2)
True

How is Python parsing and evaluating the first expression? This, evaluates the same way but this is what I would expect because == is right-associative and would evaluate to 0 in C

>>> 2 == 2 == 1
False
martineau
  • 119,623
  • 25
  • 170
  • 301
kkiz
  • 31
  • 4
  • May be related to https://stackoverflow.com/questions/47900237/why-does-1-2-3-evaluate-to-false-in-python – David Metcalfe Aug 21 '20 at 17:21
  • 3
    `==` is a comparison operator, so this is being chained, i.e. `(1 == 2) and (2 == 2)`. This is the same as `1 < 2 < 2` – juanpa.arrivillaga Aug 21 '20 at 17:22
  • 1
    The comparisons are evaluated left to right. See [Operator precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence) in the documentation. – martineau Aug 21 '20 at 17:22

1 Answers1

8

This is due to the operators chaining phenomenon

An example :

>>>  1==2
=> False
>>> 2!=3
=> True

>>> (1==2) and (2!=3)
  # False and True
=> False