Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: real order of execution for equalities/inequalities in expressions?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> (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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading