Open In App

Chaining comparison operators in Python

Last Updated : 28 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Checking more than two conditions is very common in Programming Languages. Let’s say we want to check the below condition:

a < b < c

The most common syntax to do it is as follows:

if a < b and b < c :
   {...}

In Python, there is a better way to write this using the Comparison operator Chaining. The chaining of operators can be written as follows:

if a < b < c :
    {.....}

According to associativity and precedence in Python, 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 an interpretation that is conventional in mathematics. List of comparison operators in Python:

">" | "<" | "==" | ">=" | "<=" | "!=" | "is" ["not"] | ["not"] "in"

Chaining in Comparison Operators:

  1. Comparisons yield boolean values: True or False.
  2. Comparisons can be chained arbitrarily. For example:
x < y <= z is equivalent to x < y and y <= z, 
  1. except that y is evaluated only once. (but in both cases z is not evaluated at all when x < y is found to be false).
  2. Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then an op1 b op2 c … y opN z is equivalent to a op1 b and b op2 c and … y opN z, except that each expression is evaluated at most once.
  3. Also,
a op1 b op2 c 

It doesn’t imply any kind of comparison between a and c, so

 a < b > c

is perfectly legal.

Python




# Python code to illustrate
# chaining comparison operators
x = 5
print(1 < x < 10)
print(10 < x < 20 )
print(x < 10 < x*10 < 100)
print(10 > x <= 9)
print(5 == x > 4)


Output

True
False
True
True
True

Another Example:

Python




# Python code to illustrate
# chaining comparison operators
a, b, c, d, e, f = 0, 5, 12, 0, 15, 15
exp1 = a <= b < c > d is not e is f
exp2 = a is d > f is not c
print(exp1)
print(exp2)


Output

True
False

Explanation:

In Python, chaining comparison operators is a way to simplify multiple comparison operations by stringing them together using logical operators. This is also known as “chained comparisons” or “chained comparison operators”.

In a chained comparison, two or more comparison operators are combined with logical operators such as and or or. This allows you to compare multiple values or variables with a single expression.

Here’s an example of chaining comparison operators:

Python3




x = 5
y = 10
z = 15
 
if x < y < z:
    print("y is greater than x and less than z")


Output

y is greater than x and less than z

In this example, we are using the less than (<) operator to compare x and y, and then again to compare y and z. The logical operator and is used to combine the two comparisons. The result is that the entire expression evaluates to True only if x is less than y and y is less than z. If this condition is met, the code inside the if statement will execute.

Chaining comparison operators can make your code more concise and readable, as it allows you to combine multiple comparisons into a single expression. However, it’s important to use parentheses to clarify the order of operations, as the logical operators and and or have different precedences. If parentheses are not used correctly, the expression may not evaluate as intended. 

For example:

Python3




x=5
y=10
z=15
 
if x < y or y < z and z < x:
    print("This will not be printed as expected!")


Output

This will not be printed as expected!

In this case, the and operator has a higher precedence than the or operator. Without parentheses, the expression will be evaluated as x < y or (y < z and z < x), which is not what was intended. To fix this, we can use parentheses to clarify the order of operations:

Python3




x=5
y=10
z=15
 
 
if (x < y or y < z) and z < x:
    print("This will be printed as expected")


Output

 

Now, the expression will be evaluated as (x < y or y < z) and z < x, which correctly reflects the intended logic.

Why we use Chaining comparison operators in Python:

Chaining comparison operators in Python can make code more concise and readable, as it allows you to combine multiple comparisons into a single expression. It can also help to improve code performance by reducing the number of separate comparisons that need to be performed.

Chained comparison operators are particularly useful when working with numeric data or when comparing values that have a natural order, such as dates or times. For example, when comparing two values a and b, you might want to check whether a is less than b and b is less than c. Using chained comparisons, you can express this as a < b < c instead of a < b and b < c.

Chained comparison operators can also be useful when working with boolean expressions. For example, you might want to check whether two conditions are both true. Using chained comparisons, you can express this as condition1 and condition2.

Overall, chaining comparison operators can make code more concise, easier to read, and more efficient. However, it’s important to use parentheses to clarify the order of operations, as the logical operators and and or have different precedences. If parentheses are not used correctly, the expression may not evaluate as intended.

Reference: Python 3 Documentation



Previous Article
Next Article

Similar Reads

Comparison Operators in Python
The Python operators can be used with various data types, including numbers, strings, booleans, and more. In Python, comparison operators are used to compare the values of two operands (elements being compared). When comparing strings, the comparison is based on the alphabetical order of their characters (lexicographic order).Be cautious when compa
5 min read
Implementation of Hashing with Chaining in Python
Hashing is a data structure that is used to store a large amount of data, which can be accessed in O(1) time by operations such as search, insert and delete. Various Applications of Hashing are: Indexing in database Cryptography Symbol Tables in Compiler/Interpreter Dictionaries, caches, etc. Concept of Hashing, Hash Table and Hash Function Hashing
3 min read
How to Filter rows using Pandas Chaining?
In this article, we will learn how to filter rows using Pandas chaining. For this first we have to look into some previous terms which are given below : Pandas DataFrame: It is a two-dimensional data structure, i.e. the data is tabularly aligned in rows and columns. The Pandas DataFrame has three main components i.e. data, rows, and columns.Pandas
4 min read
Python | Data Comparison and Selection in Pandas
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, and makes importing and analyzing data much easier. The most important thing in Data Analysis is comparing values and selecting data accordingly. The "==" operator works for multiple valu
2 min read
Python | Excel File Comparison
Given Two Excel Files, We want to compare the values of each column row-wise after sorting the values and print the changed column name and row number and values change. Input : Two Excel files Output : Column name : 'location' and Row Number : 0 Column name : 'location' and Row Number : 3 Column name : 'date' and Row Number : 1 Code : Python code
1 min read
Python Object Comparison : "is" vs "=="
Both "is" and "==" are used for object comparison in Python. The operator "==" compares values of two objects, while "is" checks if two objects are same (In other words two references to same object). # Python program to demonstrate working of # &quot;==&quot; # Two different objects having same values x1 = [10, 20, 30] x2 = [10, 20, 30] # Comparis
2 min read
Python | Tkinter ttk.Checkbutton and comparison with simple Checkbutton
Tkinter is a GUI (Graphical User Interface) module which comes along with the Python itself. This module is widely used to create GUI applications. tkinter.ttk is used to create the GUI applications with the effects of modern graphics which cannot be achieved using only tkinter. Checkbutton is used to select multiple options. Checkbuttons can be cr
2 min read
Python | Find Hotel Prices using Hotel price comparison API
Makcorps hotel API is used to get JSON data, to compare Hotel prices, ratings, and reviews from more than 200 websites including; Agoda.com, Hotels.com, Expedia and more. It is organized around GET Requests. One can use this API for free to get information for any hotel or any city regarding prices, ratings, reviews, historical prices and many othe
3 min read
Python | Consecutive String Comparison
Sometimes, while working with data, we can have a problem in which we need to perform comparison between a string and it's next element in a list and return all strings whose next element is similar list. Let's discuss certain ways in which this task can be performed. Method #1 : Using zip() + loop This is one way in which this task can be performe
3 min read
Face Comparison Using Face++ and Python
Prerequisites: Python Programming Language Python is a high-level general-purpose language. It is used for multiple purposes like AI, Web Development, Web Scraping, etc. One such use of Python can be Face Comparison. A module name python-facepp can be used for doing the same. This module is for communicating with Face++ facial recognition service.
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg