25. Comparison operators#

The comparison operators help to compare two objects. The comparison operators we have in Python are:

Operator

Description

==

Checks if the values of two operands are equal, if equal results True, else False

!=

Checks if the values of two operands are not equal, if not equal results True, else False

>

If the value of left operand is greater than right operand, then the result is True, else False

>=

If the value of left operand is greater than or equal to right operand, then the result is True, else False

<

If the value of right operand is greater than left operand, then the result is True, else False

<=

If the value of right operand is greater than or equal to left operand, then the result is True, else False

If you are already familiar with any other programming language, then you might have already mingled with the above comparison operators. Apart from the above comparison operators, we have two more in Python:

Operator

Description

is

Checks if both the operands are same object, if yes, result is True, else False

is not

Checks if both the operands are not same object, if yes, result is True, else False

Time for a few examples on the above mentioned operators.

25.1. == comparison operator#

The == operator checks if both the values of the operands are equal or not, if they are equal, it results in True else False.

# True

# integers
print(8 == 8)
print(5 == (1 + 4))

# float
print(0.3 == 0.30)

# str
print("🐍" == "🐍")

# tuple
print((1, 2, 3, "a") == (1, 2, 3, "a"))

# list
print([1, 2, 3] == [1, 2, 3])
True
True
True
True
True
True
# False

# integers
print(8 == 6)
print(5 == (1 + 3))

# float
print(0.3 == 8.49)

# str
print("🐍" == "😬")

# tuple
print((1, 2, 3, "a", "b") == (1, 2, 3, "a"))

# list
print([1, 2, 3] == [1, 2, 3, "πŸ‘»"])
False
False
False
False
False
False

25.2. != comparison operator#

!= is not equal to operator, which works exactly opposite to the equal operator ==.

If the values of the operands are not equal, then the result would be True else False.

print("🐍" != "🐡")
print(["πŸ•", "πŸŽ‚", "🍿"] != ["🍺", "🍻", "🍷"])
True
True

25.3. > comparison operator#

> Operator checks if the left operand value is greater than that of the right operand, if greater results in True else False.

# int
print(8 > 6)
True

Comparison of float values works the same way 🍿.

print("b" > "a")
True

We might think β€œHow the heck does string comparisons work πŸ€”?” Well, the comparison of strings work lexicographically, which mean each character in the string is compared and based on the ASCII value of the character comparison takes place..

Example:

b has higher ASCII value than a, that’s the reason we saw the result as True in the above comparison.

One more 😬:

print("Hello" > "Hey")
False

We see that the result is False as first two characters He are same, then comes the third character in each of the string which is l and y, But as per ASCII the value of l is 108 and y is 121, so y is greater and hence we see the comparison resulting False

# list
print([1, 2, 3, "a"] > [1, 2, 3, "a"])
print([1, 2, "b"] > [1, 3, "a"])
False
False

The comparison on the lists works similar to that of strings, just that each object in the lists compared 😊. If the object present in the list is iterable, then the objects inside the iterable are compared by iterating over them.

Note

We need to make sure during comparison that same type of objects are compared, else it would be raising a TypeError saying not supported πŸ™ˆ.

25.4. >= comparison operator#

This is a slice of pizza πŸ• as we already know about > operator. >= works pretty similar to > just that it returns True even if both the object’s value is equal.

# True
print(8 >= 8)
print("🐍" >= "🐍")
print([1, 2, 3, "a"] >= [1, 2, 3, "a"])

# False
print(1 >= 3)
print("Greetings Pythonist!" >= "Hey Pythonist!")
print([1, 2, 3] >= [3, 2, 1])
True
True
True
False
False
False

25.5. < comparison operator#

The thing which runs in our mind right now is β€œHey! I already know, I can figure it out from the above explanations”, No issues, let’s do it quick πŸš€

The < operator checks if the value of the right operand is greater than the left operand, if yes, then result is True, else False 😊.

# int
print(6 < 8)
True
# str
print("b" < "a")
print("Hello" < "Hey")

# list
print([1, 2, 3, "a"] < [1, 2, 3, "a"])
print([1, 2, "b"] < [1, 3, "a"])
False
True
False
True

25.6. <= comparison operator#

The <= operator checks if the value of the right operand is greater or equal to the left operand, if yes, then result is True, else False 😊.

# True
print(8 <= 8)
print("🐍" <= "🐍")
print([1, 2, 3, "a"] <= [1, 2, 3, "a"])

# False
print(3 <= 1)
print("Hey Pythonist!" <= "Greetings Pythonist!")
print([3, 2, 1] <= [1, 2, 3])
True
True
True
False
False
False

25.7. is operator#

Finally, we reached the destination to know about is operator. is operator is specific to Python, first let us see an example, then we would get into explanation 😬

a = [1, "a", None, False]  # Creating a list and assigning it to a.
b = a  # assigning the a to b.
print(f"Value of a is {a} and b is {b}")
print(a == b)
print(a is b)
Value of a is [1, 'a', None, False] and b is [1, 'a', None, False]
True
True

Hurray πŸ’₯! We see True for both a==b and a is b, Wait what πŸ™„! Then what is the difference between == and is operator?

Now, let’s see the above example code again, but slowly πŸ˜…β€¦ instead of creating a new object and assigning it to b as b= [1, "a", None, False], we have just assigned a to b. In this way, we are making a and b pointing to the same object.

You might be having trust issues with me πŸ€₯, let’s check if a and b are really the same objects programmatically 😬.

Hint

How do we find if the objects are same? The Built-in function id helps here, id(<obj>) returns the address of the object, and so if the address is same, so does the objects.

id_of_a = id(a)
id_of_b = id(b)
print(id_of_a)
print(id_of_b)
print(f"id of a is equal to id of b: {id_of_a==id_of_b}")
132059899237568
132059899237568
id of a is equal to id of b: True

Yup, that’s how the a is b returned True and we already know a == b would return True as they are having same values.

One more example:

a = [1, 2, 3]  # New object assigned to a.
b = [1, 2, 3]  # New object assigned to b.
id_of_a = id(a)
id_of_b = id(b)
print(f"id of a is {id_of_a} and b is {id_of_b}")
print(a == b)
print(a is b)
id of a is 132059899119680 and b is 132059899194368
True
False

In the above example we have assigned new lists to a and b of same values, and hence we see the result of a == b as True, but a is b returning False as id’s of a and b are different as they are different objects.

TLDR: is operator is to check for same objects, == is to check for the values of the objects.

Note

None, True and False are true constants in Python, In the complete execution of Python code, whenever and wherever we get to meet these objects, we are actually mingling with the same friends 😊. Hence, we could use is operator when we compare None, True and False.

Example:

a = None
b = None
print(a is b)
True

25.8. is not operator#

is not is the twin brother of is operator, just that it shows attitude towards is operator 😈 JK! As we know is is to find if the operands are same object, is not returns True if the operands are not same object and False if they are same object.

x = [1, 2, 3]
y = [1, 2, 3]
id_of_x = id(x)
id_of_y = id(y)
print(f"id of x is {id_of_x} and y is {id_of_y}")
print(x is not y)
id of x is 132059899125504 and y is 132059899211712
True

25.9. Note#

Important

Python does behave a little weird when integers are to be checked if they are same objects in the range of 256.

# for 256.
a = 256
b = 256
print(a is b)

# for 257.
c = 257
d = 257
print(c is d)
True
False

In the above we can see the difference, for a is b where a and b are 256, we see the result as True. But for c is d where c and d are 257, we see that the result if False.

The reason for this is Python caches the integer objects from 0 to 256, so whenever we assign an integer between 0 and 256, Python uses the same integer object it has created everytime 😊. No worries, we can use == for integers which works pretty fine as we would be most concerned about the value of the integer 😊.