0%

16- Comparison Operators in Python

Compare numbers, strings, and other values. Get True or False answers. The foundation of every decision in your code.

You have two numbers. Which one is larger? You have two strings. Are they the same? You have a variable. Does it equal a specific value? Comparison operators answer these questions. They take two values, compare them, and return a boolean (True or False). No exceptions. No maybe. Just truth or falsehood. These operators are the building blocks of logic. Every if statement, every while loop, every conditional expression uses comparison operators under the hood. Master them, and you master decision-making in Python.

🕯️ Magic Note

Comparison operators work on more than just numbers. You can compare strings, lists, tuples, and even custom objects. Python’s designers built consistency into the language: if it makes sense to compare two things, you probably can.

The Six Comparison Operators
Python provides six comparison operators. They all return booleans. They all can be chained together.
OperatorMeaningExample (x=5, y=10)Result
==Equal tox == yFalse
!= Not equal tox != yTrue
>Greater thanx > yFalse
<Less thanx < yTrue
>=Greater than or equal tox >= yFalse
<=Less than or equal tox <= yTrue

Python

# Basic comparisons with numbers

a = 10

b = 20

c = 10

print(a == b) # False

print(a == c) # True

print(a != b) # True

print(a > b) # False

print(a < b) # True

print(a >= c) # True

print(b <= a) # False

⚠️ Do not confuse the assignment operator = with the equality comparison operator ==. This is the most common typo in programming. x = 5 assigns 5 to x. x == 5 checks if x equals 5.
Comparing Numbers
Numbers compare as you would expect in mathematics. Integers and floats can be compared directly.

Python

print(5 > 3) # True

print(5 < 3) # False

print(5 == 5.0) # True (int and float can be equal)

print(5 == “5”) # False (different types)

# Negative numbers work normally

print(-5 < -3) # True (-5 is less than -3)

print(-10 > -20) # True (-10 is greater than -20)

# Floating point precision warning

print(0.1 + 0.2 == 0.3) # False (due to floating point precision)

print(0.1 + 0.2 < 0.3) # False (it is actually slightly greater)

💡 Never compare floats directly for equality. Instead, check if the absolute difference is very small: abs(a – b) < 1e-9. This accounts for floating point precision errors.
Comparing Strings
Strings compare lexicographically (dictionary order) based on Unicode values of characters. This means order is determined by the alphabet, but uppercase letters come before lowercase letters.

Python

# String equality

print(“hello” == “hello”) # True

print(“hello” == “Hello”) # False (case-sensitive)

print(“hello” != “world”) # True

# Lexicographic order (alphabetical)

print(“apple” < “banana”) # True (‘a’ comes before ‘b’)

print(“car” > “bus”) # True (‘c’ comes after ‘b’)

print(“cat” < “cat”) # False (equal)

# Case sensitivity (uppercase comes before lowercase in Unicode)

print(“Apple” < “apple”) # True (‘A’ has value 65, ‘a’ has 97)

print(“Zebra” < “apple”) # True (‘Z’ has value 90, ‘a’ has 97)

🕯️ Magic Note

String comparison is based on Unicode code points. This means digits come before uppercase letters, and uppercase letters come before lowercase letters. For case-insensitive comparison, convert both strings to the same case: str1.lower() == str2.lower().

Comparing Lists and Tuples
Lists and tuples compare element by element. The first differing element determines the result. If all elements are equal and the lengths are the same, they are equal.

Python

# List comparisons

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

print([1, 2, 3] == [3, 2, 1]) # False (order matters)

print([1, 2] < [1, 2, 3]) # True (first list is prefix of second)

print([1, 2, 4] > [1, 2, 3]) # True (4 > 3 at third position)

# Tuple comparisons (same logic)

print((1, 2, 3) == (1, 2, 3)) # True

print((1, 2) < (1, 2, 3)) # True

⚠️ Comparing lists or tuples of different types (like a list with a tuple) raises a TypeError. You cannot compare a list to a tuple even if they contain the same elements.
Comparing Different Types
In Python 3, comparing different incompatible types (like a number and a string) raises a TypeError. This is different from Python 2, which allowed it (with weird results).

Python

# Comparing different types (Python 3+)

# print(5 < “10”) # TypeError: ‘<‘ not supported between instances of ‘int’ and ‘str’

# But numeric types work together

print(5 < 10.5) # True (int and float can compare)

print(5 == 5.0) # True

# Booleans are a subclass of int

print(True == 1) # True

print(False == 0) # True

print(True > 0) # True

Chaining Comparison Operators
Python allows you to chain comparison operators. This is a unique and readable feature. You can write a < b < c instead of a < b and b < c.

Python

x = 5

# Chained comparisons (elegant and readable)

print(1 < x < 10) # True (1 < 5 and 5 < 10)

print(1 < x > 4) # True (1 < 5 and 5 > 4)

print(10 > x >= 5) # True (10 > 5 and 5 >= 5)

# This is equivalent to:

print(1 < x and x < 10) # True

# Chaining with different operators

print(x == 5 < 10) # True (x == 5 and 5 < 10)

print(x == 5 > 10) # False (x == 5 is True, but 5 > 10 is False)

🕯️ Magic Note

Chained comparisons are not just syntactic sugar. Each expression is evaluated only once. In a < b < c, b is evaluated only once. This is different from a < b and b < c where b might be evaluated twice if it is a function call with side effects.

Python

# Chaining with functions (function called once)

def get_value():

print(“get_value was called”)

return 5

result = 1 < get_value() < 10

# “get_value was called” prints only once

print(result) # True

Comparing with None
Use is and is not to compare with None. Do not use == or != .

Python

value = None

# Correct way to check for None

if value is None:

print(“Value is None”)

if value is not None:

print(“Value exists”)

# Works but not recommended (could be ambiguous)

if value == None: # Avoid this

print(“This works but is not Pythonic”)

💡 Use is for None, True, and False. Use == for everything else. This is a Python convention that makes your code more explicit and correct.
Comparing with Booleans
Do not compare boolean values to True or False directly. Use the boolean variable itself or the not operator.

Python

is_ready = True

# Not recommended (redundant)

if is_ready == True:

print(“Ready”)

# Pythonic way

if is_ready:

print(“Ready”)

if not is_ready:

print(“Not ready”)

🕯️ Magic Note

Comparing a boolean to True or False is redundant because the boolean itself already is True or False. The extra comparison adds no value and makes the code less readable.

The is vs == Difference
== compares values (equality). is compares identity (whether two variables refer to the same object in memory). For most cases, you want ==.

Python

a = [1, 2, 3]

b = [1, 2, 3]

c = a

# == compares values (the contents)

print(a == b) # True (same values)

print(a == c) # True (same values)

# is compares identity (the same object in memory)

print(a is b) # False (different objects in memory)

print(a is c) # True (c refers to the same object as a)

# Small integers are cached (-5 to 256), so is may work by accident

print(256 is 256) # True (cached)

print(257 is 257) # May be True or False (implementation dependent)

⚠️ Do not use is for comparing numbers or strings. It may work by accident due to Python’s internal caching, but it is not guaranteed. Use == for value comparison.
Common Mistakes with Comparison Operators
  • Using = instead of == in conditions: if x = 5: (SyntaxError)
  • Comparing floats directly with == (use tolerance instead)
  • Forgetting that string comparison is case-sensitive
  • Using is instead of == for value comparison
  • Comparing different incompatible types (TypeError)
  • Writing x < y > z when you meant x < y and y > z (works but may confuse readers)
Check Your Understanding
  • What is the difference between = and ==?
  • Why does 0.1 + 0.2 == 0.3 return False?
  • What is the result of “Cat” < “cat” and why?
  • Write a chained comparison that checks if x is between 10 and 20 (inclusive).
  • When should you use is instead of ==?
  • What happens if you compare a number to a string in Python 3?

⚡ Whisper

Every decision begins with a comparison. Is this larger than that? Are they equal? Does this value match what I expect? These are simple questions, but they build the skeleton of logic. One comparison gives you a fork in the road: True leads one way, False leads another. Two comparisons give you a map. Three comparisons give you a labyrinth of possibilities. Learn to ask the right questions. Learn to chain your comparisons elegantly. A program without comparisons is a straight line with no turns. A program with comparisons is a living thing that chooses its own path. Be the weaver of choices. Master the comparison.

Related posts