Explaining Chain Comparisons in Python
The aim of this page📝 is to explain chain comparisons in Python — a feature not many languages have.
1 min readFeb 7, 2023
- Taking a class on Python OOP, I found the following snippet and had no idea about the possibility of doing this up until now
def celsius(self,value):
if not (
HeatedRefrigeratedShippingContainer.MIN_CELSIUS
<= value
<= RefrigeratedShippingContainer.MAX_CELSIUS
):
- The teacher said
The body of our setter uses Python’s convenient chained comparisons to ensure that the proposed temperature value lies within the inclusive range specified by MIN_CELSIUS and MAX_CELSIUS class attributes
- Chained comparisons? The official docs don’t call it that
Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics
— from 6. Expressions — Python 3.11.1 documentation
- And of course, Lex Friedman is a big Python fan and has a video exactly on this, see Best hidden feature of Python < Chaining comparison operators < YouTube