Sitemap

Member-only story

Chained Comparison in Python

2 min readMar 2, 2025
Photo by Saif71.com on Unsplash

When writing conditions in Python, you often need to compare multiple values. Instead of using multiple logical operators, Python offers a cleaner and more intuitive way to perform comparisons — chained comparisons.

Read for free: https://allwin-raju.medium.com/chained-comparison-in-python-18d0816cba4b?sk=7b9e05ee4c420e6e06cdbde3dfab0b7a

What is Chained Comparison?

Chained comparison allows you to combine multiple comparison operations in a single, readable expression, much like mathematical notation. For example:

x = 10
print(5 < x < 20) # True

This statement is equivalent to:

(5 < x) and (x < 20)

Python evaluates 5 < x < 20 as a sequence of two conditions (5 < x and x < 20) joined by an and operator, making the code more concise and readable.

Benefits of Chained Comparison

  • Improves readability — Expressions look more natural and resemble mathematical notation.
  • Reduces redundancy — No need to repeat variables in multiple conditions.
  • Enhances performance — Python evaluates expressions from left to right and stops early if a condition fails.

Examples of Chained Comparisons

--

--

No responses yet