The Wayback Machine - https://web.archive.org/web/20240816200002/https://www.geeksforgeeks.org/chaining-comparison-operators-python/
Open In App

Chaining comparison operators in Python

Last Updated : 28 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 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
Comparison of Python with Other Programming Languages
Python is an easily adaptable programming language that offers a lot of features. Its concise syntax and open-source nature promote readability and implementation of programs which makes it the fastest-growing programming language in current times. Python has various other advantages which give it an edge over other popular programming languages su
3 min read
String Comparison in Python
String comparison is a fundamental operation in any programming language, including Python. It enables us to ascertain strings' relative positions, ordering, and equality. Python has a number of operators and techniques for comparing strings, each with a specific function. We will examine numerous Python string comparison methods in this article an
5 min read
Comparison of Java with other programming languages
Java is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in ev
4 min read
Python2 vs Python3 | Syntax and performance Comparison
Python 2.x has been the most popular version for over a decade and a half. But now more and more people are switching to Python 3.x. Python3 is a lot better than Python2 and comes with many additional features. Also, Python 2.x is becoming obsolete this year. So, it is now recommended to start using Python 3.x from now-onwards. Still in dilemma? Ev
4 min read
When to Use Django? Comparison with other Development Stacks
Prerequisite - Django Introduction and Installation When to Use Django and Why? After getting to know the basics of Python, one should know when to use Django and why? Django is a high-level python based web framework which allows you to quickly create web applications without all of the installation or dependency problems that you normally will fi
4 min read
Comparison of FastAPI with Django and Flask
For starters, as you may know, Python is an interpreted programming language that is becoming more and more popular for building web applications. However, there are numerous web frameworks to choose from but they all have different use cases. In this article, we will look at 3 frameworks which are : Django - It follows the model-template-view arch
4 min read
Merging and Updating Dictionary Operators in Python 3.9
Python 3.9 is still in development and scheduled to be released in October this year. On Feb 26, alpha 4 versions have been released by the development team. One of the latest features in Python 3.9 is the merge and update operators. There are various ways in which Dictionaries can be merged by the use of various functions and constructors in Pytho
3 min read
Python 3 - Logical Operators
Logical Operators are used to perform certain logical operations on values and variables. These are the special reserved keywords that carry out some logical computations. The value the operator operates on is known as Operand. In Python, they are used on conditional statements (either True or False), and as a result, they return boolean only (True
4 min read
How To Do Math in Python 3 with Operators?
Python3 provides us data types like integer and float along with various operators to perform mathematical calculations for graph plotting, machine learning algorithms, Statistical, data analytical purposes. An operator is a symbol that performs specific operations, which is very useful if one is frequently dealing with numbers. Operator precedence
5 min read
Precedence and Associativity of Operators in Python
In Python, operators have different levels of precedence, which determine the order in which they are evaluated. When multiple operators are present in an expression, the ones with higher precedence are evaluated first. In the case of operators with the same precedence, their associativity comes into play, determining the order of evaluation. Opera
4 min read
Augmented Assignment Operators in Python
An assignment operator is an operator that is used to assign some value to a variable. Like normally in Python, we write "a = 5" to assign value 5 to variable 'a'. Augmented assignment operators have a special role to play in Python programming. It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator
4 min read
Inplace Operators in Python | Set 1 (iadd(), isub(), iconcat()...)
Python in its definition provides methods to perform inplace operations, i.e. doing assignments and computations in a single statement using an operator module. Example x += y is equivalent to x = operator.iadd(x, y) Inplace Operators in PythonBelow are some of the important Inplace operators in Python: iadd()isub()iconcat()imul()itruediv()imod()ia
3 min read
Inplace Operators in Python | Set 2 (ixor(), iand(), ipow(),…)
Inplace Operators in Python | Set 1(iadd(), isub(), iconcat()…) More functions are discussed in this articles. 1. ixor() :- This function is used to assign and xor the current value. This operation does "a^ = b" operation. Assigning is not performed in case of immutable containers, such as strings, numbers and tuples. 2. ipow() :- This function is
3 min read
Inplace vs Standard Operators in Python
Inplace Operators - Set 1, Set 2Normal operators do the simple assigning job. On other hand, Inplace operators behave similarly to normal operators except that they act in a different manner in case of mutable and Immutable targets. The _add_ method, does simple addition, takes two arguments, returns the sum, and stores it in another variable witho
3 min read
Increment += and Decrement -= Assignment Operators in Python
If you're familiar with Python, you would have known Increment and Decrement operators ( both pre and post) are not allowed in it. Python is designed to be consistent and readable. One common error by a novice programmer in languages with ++ and -- operators are mixing up the differences (both in precedence and in return value) between pre and post
3 min read
Python Operators
In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators.  OPERATORS: These are the special symbols. Eg- + , * , /, etc.OPERAND: It is the value on which the operato
12 min read
Python Membership and Identity Operators
There is a large set of Python operators that can be used on different datatypes. Sometimes we need to know if a value belongs to a particular set. This can be done by using the Membership and Identity Operators. In this article, we will learn about Python Membership and Identity Operators. Table of Content Python Membership OperatorsPython IN Oper
7 min read
Python Bitwise Operators
Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic and logical computations. The value the operator operates on is known as the Operand.  Python Bitwise OperatorsPython bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into
6 min read
Division Operators in Python
Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. Division Operators in PythonThere are two types of division operators: Float divisionInteger division( Floor division)When an integer is divided, the
6 min read
Python Logical Operators
Python logical operators are used to combine conditional statements, allowing you to perform operations based on multiple conditions. These Python operators, alongside arithmetic operators, are special symbols used to carry out computations on values and variables. In this article, we will discuss logical operators in Python definition and also loo
6 min read
Python Arithmetic Operators
The Python operators are fundamental for performing mathematical calculations in programming languages like Python, Java, C++, and many others. Arithmetic operators are symbols used to perform mathematical operations on numerical values. In most programming languages, arithmetic operators include addition (+), subtraction (-), multiplication (*), d
5 min read
Assignment Operators in Python
The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python. Operators Sign Description SyntaxAssignment Operator = Assi
11 min read
Operators Precedence in Scala
An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Which operator is performed first in an expression with more than one operators with different precedence is determined by operator precedence. For example, 10 + 20 * 30 is calculated as 10 + (20 *
3 min read
Boolean Operators - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variable
5 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg