Python Comparison Operators are fundamental and crucial elements of conditional statements. They are utilized to assess two values and yield a boolean outcome, either True or False. Aside from conditional statements, these operators are also extensively applied in decision-making, control flow, validation, sorting, filtering, and beyond. Within this article, you will gain insights into Python comparison operators, their syntax, and their practical applications in detail.
Comparison operators represent one of the numerous categories of Python operators. They facilitate the comparison of two values and assess their relationship. These operators are predominantly employed in conditional statements such as if, elif, and while to govern the program’s flow based on specified criteria. The output of these expressions consistently yields a boolean value, either True or False. In Python, there exist six primary types of Comparison Operators.
Types of Comparison Operators in Python
In Python, the comparison operators include equal to, not equal to, greater than, less than, greater than or equal to, and less than or equal to. Let us explore them with code snippets.
Equal to (==) Operator
This operator verifies if the two values, or operands, are equal. If they are indeed equal, it returns True; otherwise, it returns False.
function closeoutput62420() {
var code = editor62420.getSession().getValue();
jQuery(“.maineditor62420 .code-editor-output”).hide();
}
// Attach event listeners to the buttons
document.getElementById(“copyBtn62420”).addEventListener(“click”, copyCodeToClipboard62420);
document.getElementById(“runBtn62420”).addEventListener(“click”, runCode62420);
document.getElementById(“closeoutputBtn62420”).addEventListener(“click”, closeoutput62420);
Result:
Clarification: In this instance, since x does not match 5, the if block condition was verified, thus the code within the if block was executed. Conversely, y equaled 5, so there was no output in the console.
Greater Than (>) Operator
This operator will yield True if the first operand exceeds the second operand. If it does not, it will simply return False.
Illustration:
Python
Code Duplicated!
var isMobile = window.innerWidth “);
editor38218.setValue(decodedContent); // Set the default text
editor38218.clearSelection();
editor38218.setOptions({
maxLines: Infinity
});
function decodeHTML38218(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard38218() {
const code = editor38218.getValue(); // Acquire code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(“.maineditor38218 .copymessage”).show();
setTimeout(function() {
jQuery(“.maineditor38218 .copymessage”).hide();
}, 2000);
}).catch(err => {
console.error(“Issue duplicating code: “, err);
});
}
// Additional functionality not included to preserve space.
jQuery.ajax({
url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”,
type: “post”,
data: {
language: “python”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action: “compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];
jQuery(“.output38218”).html(“
" + data + "");
jQuery(".maineditor38218 .code-editor-output").show();
jQuery("#runBtn38218 i.run-code").hide();
}
})
}
function closeOutput38218() {
var code = editor38218.getSession().getValue();
jQuery(".maineditor38218 .code-editor-output").hide();
}
// Bind event listeners to the buttons
document.getElementById("copyBtn38218").addEventListener("click", copyCodeToClipboard38218);
document.getElementById("runBtn38218").addEventListener("click", runCode38218);
document.getElementById("closeOutputBtn38218").addEventListener("click", closeOutput38218);
Result:
Analysis: In this case, since b is larger than a, it meets the condition in the elif block, thus executing the elif block.
Less Than (<) Operator
This operator evaluates the two values and determines if the left value is less than the right value. If true, it yields True; otherwise, it produces False.
Illustration:
Python
Code Copied!
Result:
Analysis: In this scenario, since a was lesser than b, the ‘if’ block was executed.
Greater Than or Equal to (>=) Operator
This operator combines the equal to operator with the greater than operator. When utilized in an expression, it returns True if the first operand is greater than or equal to the second operand.
Illustration:
Python
Code Copied!
``````html
Output:
Explanation: Here, a was greater than or equal to b. Hence, it was displayed on the output console following the condition verification.
Less Than or Equal to (<=) Operator
This operator is composed of the ‘less than’ sign and the ‘equal to’ sign. This operator returns True for instances where the left operand is lesser than or equal to the right operand. Otherwise, it returns False.
Example:
Python
Code Duplicated!
Output:
Description: In this case, a is smaller than b. This made the condition inside the if statement true. Consequently, the if block was executed.
Chaining Comparison Operators in Python
In Python, you can link various comparison operators similarly to how we do in mathematics without needing parentheses. This indicates that you can express (a > 10) and (a < 20) as 10 < a < 20, and both will yield the same outcome. The benefit of this comparison is that Python evaluates each condition from left to right and will halt as soon as any portion of the chain fails.
Mechanism: The interpreter automatically inserts a logical operator between the comparison operators when chaining them. Therefore, a < b < c is interpreted as (a < b) and (b < c).
Sample Code:
Python
Code Copied!
Outcome:
Interpretation: In this instance, the student's grade was 82. Based on the condition, the output was produced.
Summary
Operator
Name
Description
Example
Outcome
==
Equal to
Verifies if two values are equivalent
5 == 5
True
!=
Not equal to
Verifies if two values are not equivalent
5 != 3
True
>
Greater than
True if the left operand exceeds
7 > 3
True
<
Less than
True if the left operand is lesser
4 < 9
True
>=
Greater than or equal to
True if left is greater or equivalent
10 >= 10
True
<=
Less than or equal to
True if the left is lesser or equivalent
6 <= 6
True
Comparison Operators with Various Data Types in Python
Python enables you to compare different data types such as strings, tuples, and lists in addition to integers. This permits comparisons between a string and another string, a tuple with another tuple, and a list with another list. However, comparing incompatible data types is not permissible. For instance, you cannot compare a string to a tuple, etc.
Strings in Python
When utilizing comparison operators with strings, Python compares each character based on their ASCII code. This method is known as Lexicographical Comparison. Note that uppercase letters appear before lowercase letters in the ASCII ordering.
Sample Code:
Python
``````html
Code Duplicated!
var isMobile = window.innerWidth ");
editor61821.setValue(decodedContent); // Assign the initial text
editor61821.clearSelection();
editor61821.setOptions({
maxLines: Infinity
});
function decodeHTML61821(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard61821() {
const code = editor61821.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor61821 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor61821 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Issue copying code: ", err);
});
}
function runCode61821() {
var code = editor61821.getSession().getValue();
function closeOutput61821() {
var code = editor61821.getSession().getValue();
jQuery(".maineditor61821 .code-editor-output").hide();
}
// Add event listeners for the buttons
document.getElementById("copyBtn61821").addEventListener("click", copyCodeToClipboard61821);
document.getElementById("runBtn61821").addEventListener("click", runCode61821);
document.getElementById("closeoutputBtn61821").addEventListener("click", closeOutput61821);
Outcome:
Clarification: Here, the initial letters M and D are evaluated. The ASCII value of M is 77, while D is 68. Given that 77 > 68, "Mumbai" ranks after "Delhi" alphabetically.
Tuples and Lists in Python
With ordered data types such as tuples and lists, the interpreter assesses each element sequentially from left to right. It continues until it identifies a false comparison and returns False at that point.
Illustration:
Python
Code Duplicated!
var isMobile = window.innerWidth ");
editor66168.setValue(decodedContent); // Assign the initial text
editor66168.clearSelection();
editor66168.setOptions({
maxLines: Infinity
});
function decodeHTML66168(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard66168() {
const code = editor66168.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor66168 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor66168 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Issue copying code: ", err);
});
}
function runCode66168() {
var code = editor66168.getSession().getValue();
function closeoutput66168() {
var code = editor66168.getSession().getValue();
jQuery(".maineditor66168 .code-editor-output").hide();
}
// Assign event listeners to the buttons
document.getElementById("copyBtn66168").addEventListener("click", copyCodeToClipboard66168);
document.getElementById("runBtn66168").addEventListener("click", runCode66168);
document.getElementById("closeoutputBtn66168").addEventListener("click", closeoutput66168);
Output:
Explanation: In this scenario, in tuples, a is less than b as the third element in a is less than that in b. In the final example, list 1 contains only two items, whereas list 2 contains three. Hence, list1 is regarded as less than list2. Shorter lists are deemed smaller if all preceding elements are identical.
Boolean in Python
In Python, boolean values function similarly to integers. The True value corresponds to the integer 1, while the False value corresponds to 0. Therefore, when we compare boolean values using the less than or greater than operator, the results will reflect this.
Example:
Python
Code Copied!
var isMobile = window.innerWidth ");
editor80817.setValue(decodedContent); // Initialize the text
editor80817.clearSelection();
editor80817.setOptions({
maxLines: Infinity
});
function decodeHTML80817(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard80817() {
const code = editor80817.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor80817 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor80817 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
function closeoutput80817() {
var code = editor80817.getSession().getValue();
jQuery(".maineditor80817 .code-editor-output").hide();
}
// Assign event listeners to the buttons
document.getElementById("copyBtn80817").addEventListener("click", copyCodeToClipboard80817);
document.getElementById("runBtn80817").addEventListener("click", runCode80817);
document.getElementById("closeoutputBtn80817").addEventListener("click", closeoutput80817);
Output:
Explanation: Here, True is interpreted as 1, while False is viewed as 0. The outcomes of comparisons mirror their integer representations (1 for True, 0 for False).
Real-World Instance of Comparison Operators in Python
Comparison operators are ubiquitous in scenarios involving conditional statements. These operators examine conditions based on which further actions are determined. In this instance, we are utilizing the Bubble sort algorithm to demonstrate the functionality of comparison operators. Our goal is to sort the students' grades in an ascending manner to establish the rankings.
Bubble sort evaluates two adjacent values through the greater than (>) comparison operator to ascertain whether the specified list is ordered or unordered.
Example:
Example:
Python
Code Copied!
var isMobile = window.innerWidth ");
editor62364.setValue(decodedContent); // Set the default text
editor62364.clearSelection();
editor62364.setOptions({
maxLines: Infinity
});
function decodeHTML62364(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard62364() {
const code = editor62364.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
function closeoutput62364() {
var code = editor62364.getSession().getValue();
jQuery(".maineditor62364 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn62364").addEventListener("click", copyCodeToClipboard62364);
document.getElementById("runBtn62364").addEventListener("click", runCode62364);
document.getElementById("closeoutputBtn62364").addEventListener("click", closeoutput62364);
Output:
Explanation: Here, we assessed the neighboring values and organized the list in increasing order based on the students’ scores.
Conclusion
Comparison operators are fundamental in programming, particularly for operations like sorting and searching, which are among the most frequent tasks. They aid in establishing conditions that guide the flow of control depending on how comparisons evaluate. Mastery of comparison operators is crucial for crafting clear, logical Python code that adapts to data. Comprehending and practicing these operators creates a foundation for building intelligent, responsive applications that evaluate and act based on diverse data scenarios.
To enhance your capabilities, explore this Python training course and acquire hands-on experience. Additionally, prepare for job interviews with Python interview questions curated by industry specialists.
Python Comparison Operators – FAQs
Q1. Are string comparisons case-sensitive?
Yes, since uppercase characters possess lower ASCII values than their lowercase counterparts.
Q2. What occurs if I compare incompatible types, such as int and str?
It will trigger a TypeError in Python.
Q3. Is it possible to chain comparison operators like a
Yes, Python permits chaining and interprets it as (a
Q4. Can I compare lists or tuples?
Yes, in Python, they are compared element-wise from left to right, and they yield a boolean value, i.e., True or False.
Q5. What do comparison operators yield in Python?
They provide a boolean value, i.e., True or False.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.