Comparison Operators
Get familiar with comparisons in Python using comparison operators, including basic comparisons, as well as the 'is' and 'is not' operators.
We'll cover the following...
Comparison operators can be used to compare values in mathematical terms. The precedence of comparison operator is same.
Symbol | Operator |
| Greater Than |
| Less Than |
| Greater Than or Equal To |
| Less Than or Equal To |
| Equal To |
| Not Equal To |
Output of comparison operators
The result of a comparison is always a bool. If the comparison is correct, the value of the bool will be True
. Otherwise, its value will be False
.
Try it yourself
Let’s look at a few examples. Our AI Mentor can explain the code as well.
num1 = 5num2 = 10num3 = 10print(num2 > num1)print(num1 > num2)print(num2 == num3)print(num3 != num1)print(3 + 10 == 5 + 5)print(3 <= 2)
Identity operators
In Python, the is
and is not
operators are used to compare the memory locations of two objects. They help determine if two variables reference the same object in memory. Here’s an example demonstrating how is
and is not
operators are used and how they differ from the equality operator.
original_list = [1, 2, 3]same_reference_list = original_listdifferent_list = [1, 2, 3]reordered_list = [1, 3, 2]print(original_list is same_reference_list)print(original_list is different_list)print(original_list == different_list)print(original_list == reordered_list)# Example with integersfirst_number = 10second_number = 20third_number = 10print(first_number is not second_number)print(first_number is not 10)same_reference_number = first_numberprint(same_reference_number is first_number)