Explaining Chain Comparisons in Python

The aim of this page📝 is to explain chain comparisons in Python — a feature not many languages have.

Pavol Kutaj
1 min readFeb 7, 2023
The weirdness of generative AI utilized as a memorizing technique?
  • 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

LINKS

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com