0

Imagine this "sneaky" python code:

>>> 1 == 2 < 3
False

According to Python documentation all of the operators in, not in, is, is not, <, <=, >, >=, !=, == have the same priority, but what happens here seems contradictory.

I get even weirder results after experimenting:

>>> (1 == 2) < 3
True
>>> 1 == (2 < 3)
True

What is going on?

(Note)

>>> True == 1
True
>>> True == 2
False
>>> False == 0
True
>>> False == -1
False

Boolean type is a subclass of int and True represents 1 and False represents 0.

This is likely an implementation detail and may differ from version to version, so I'm mostly interested in python 3.10.

oBrstisf8o
  • 124
  • 10
  • 3
    Comparison chaining: `1 == 2 < 3` is equivalent to `1 == 2 and 2 < 3`, not either of the explicitly parenthesized versions you are trying. `2 < 3` never gets evaluated, because `1 == 2` is false. – chepner Jun 07 '23 at 17:16

1 Answers1

1

Python allows you to chain conditions, it combines them with and. So

1 == 2 < 3

is equivalent to

1 == 2 and 2 < 3

This is most useful for chains of inequalities, e.g. 1 < x < 10 will be true if x is between 1 and 10.

WHen you add parentheses, it's not a chain any more. So

(1 == 2) < 3

is equivalent to

False < 3

True and False are equivalent to 0 and 1, so False < 3 is the same as 0 < 3, which is True.

Similarly,

1 == (2 < 3)

is equivalent to

1 == True

which is equivalent to

1 == 1

which is obviously True.

Barmar
  • 741,623
  • 53
  • 500
  • 612