DevHireLab
Tutorials
BootcampProblemsCode SimulatorAI InterviewSoonContact
DevHireLab
Tutorials
BootcampProblemsCode SimulatorAI InterviewSoonContact
Getting Started
01
What is Python and Why Learn It in 2026
02
Installing Python on Windows, Mac, and Linux
03
Setting up VS Code / PyCharm for Python
04
Understanding the Python Interpreter and REPL
05
Writing and Running Your First Python Program
06
Python Syntax and Indentation Rules
Variables and Data Types
01
Variables and Naming Conventions in Python
02
Numbers in Python (int, float, complex)
03
Strings and String Methods in Python
04
Booleans in Python
05
Type Conversion / Casting in Python
06
Understanding the None Type in Python
Operators
01
Arithmetic Operators in Python
02
Comparison Operators in Python
03
Logical Operators in Python
04
Assignment Operators in Python
05
Bitwise Operators in Python
06
Identity (is) and Membership (in) Operators
07
Walrus Operator (:=) in Python
Input, Output & Strings
01
input() and print() Functions in Python
02
f-strings and String Formatting in Python
03
String Slicing and Indexing in Python
04
Common String Methods (split, join, strip, replace)
05
Escape Characters in Python Strings
Control Flow
01
if, elif, else Statements in Python
02
Nested Conditionals in Python
03
for Loops in Python
04
while Loops in Python
05
break, continue, and pass Statements
06
Loop with else Clause in Python
07
match-case (Structural Pattern Matching)
Data Structures
01
Python Lists: Creation, Indexing, Slicing, Methods
02
Python Tuples and Immutability
03
Python Sets and Set Operations
04
Python Dictionaries: Keys, Values, and Methods
05
List Comprehensions in Python
06
Dictionary & Set Comprehensions in Python
07
Working with Nested Lists and Dictionaries
Functions
01
Defining and Calling Functions in Python
02
Function Arguments: Positional, Keyword, Default
03
*args and **kwargs in Python
04
Return Statements in Python Functions
05
Lambda Functions in Python
06
Recursion in Python
07
Variable Scope: Local, Global, Nonlocal
08
Docstrings and Function Annotations
Functional Programming Basics
01
map(), filter(), and reduce() in Python
02
Closures in Python Explained
03
Python Decorators: Basic to Advanced
04
Generators and yield in Python
Object-Oriented Programming (OOP)
01
Classes and Objects in Python
02
The init Constructor in Python
03
Instance vs Class Variables in Python
04
Inheritance in Python (Single, Multiple, Multilevel)
05
Polymorphism in Python
06
Encapsulation in Python
07
Abstraction in Python with the abc Module
08
Magic/Dunder Methods in Python
09
Static and Class Methods in Python
10
The @property Decorator in Python
11
Python Dataclasses Explained
Error Handling
01
try, except, finally in Python
02
Handling Multiple Exceptions in Python
03
Raising Custom Exceptions in Python
04
Understanding Python's Exception Hierarchy
05
Assertions in Python
File Handling
01
Reading and Writing Text Files in Python
02
Working with the with Statement in Python
03
Working with CSV Files in Python
04
Working with JSON Files in Python
05
Working with Directories (os, pathlib) in Python
Modules and Packages
01
Importing Built-in Modules in Python
02
Creating Your Own Modules in Python
03
Understanding Packages and init.py
04
Python Standard Library Overview
05
Installing Packages with pip
Advanced Core Concepts
01
Iterators and Iterables in Python
02
Context Managers in Python (with, contextlib)
03
Multithreading Basics in Python
04
Multiprocessing Basics in Python
05
Asyncio Basics: async/await in Python
06
Memory Management and Garbage Collection in Python
07
Type Hints in Python (typing module)

Comparison Operators in Python

Every conditional in your code — every if, every loop that runs "while" something is true — depends on python comparison operators. They're deceptively simple on the surface, but a couple of them (particularly == versus is) trip up even developers who've been writing Python for a while. This article covers all six comparison operators, how they behave across different data types, and the identity-vs-equality distinction that causes so much confusion.

What Are Comparison Operators?

A comparison operator takes two values and always returns a Boolean: True or False. They're also called relational operators, since they describe the relationship between two values — equal, greater, less, and so on.

print(5 > 3)   # True

These operators are the foundation of conditional logic throughout Python — every if statement, every while loop condition, ultimately comes down to a comparison like this one.

Python has six comparison operators:

==   # equal to
!=   # not equal to
>    # greater than
<    # less than
>=   # greater than or equal to
<=   # less than or equal to

The Six Comparison Operators, One by One

== (equal to)

Checks whether two values are equal:

print(5 == 5)   # True
print(5 == 3)   # False

The classic beginner mistake: confusing == (comparison) with = (assignment). This is one of the most common early errors:

x = 5

if x = 5:   # SyntaxError — this should be ==
    print("x is 5")

Python catches this particular mistake with a syntax error rather than silently doing the wrong thing, which is a small mercy — but it's worth burning the distinction into memory early: single = assigns, double == compares.

!= (not equal to)
print(5 != 3)   # True
print(5 != 5)   # False
>, <, >=, <=
print(5 > 3)    # True  — greater than
print(5 < 3)    # False — less than
print(5 >= 5)   # True  — greater than or equal to
print(5 <= 4)   # False — less than or equal to
Bonus: python string comparison

Strings can be compared with these same operators, evaluated lexicographically — essentially, alphabetical order, based on the underlying character codes:

print("apple" < "banana")   # True — 'a' comes before 'b'
print("apple" == "apple")   # True
print("Apple" == "apple")   # False — comparison is case-sensitive

That last example is worth remembering: string comparison is case-sensitive by default, since uppercase and lowercase letters have different underlying character codes. If you need a case-insensitive comparison, convert both sides with .lower() or .upper() first.

Comparing Different Data Types

Compatible numeric types

Comparisons work seamlessly across compatible numeric types, the same way arithmetic does:

print(5 == 5.0)     # True — int and float compare by value
print(5 < 5.5)       # True
Incompatible types raise errors

Equality checks (==, !=) are lenient — they'll compare almost anything and simply return False if the types don't match in any meaningful way, rather than raising an error:

print(5 == "5")    # False — no error, just not equal
print([1, 2] == "hello")   # False

But ordering operators (<, >, <=, >=) are stricter. Trying to determine whether one incompatible type is "greater than" another often raises a TypeError, since there's no sensible way to order them:

print(5 < "5")
# TypeError: '<' not supported between instances of 'int' and 'str'

The general rule: == and != work broadly across almost any two values, while <, >, <=, and >= require the values to be meaningfully orderable — usually meaning they need to be the same type, or at least compatible numeric types.

Chaining Comparisons

Python allows a genuinely elegant shorthand that a lot of other languages don't support: chaining multiple comparisons in a single, readable expression.

number = 15

# Chained comparison — reads naturally
if 10 <= number <= 20:
    print("Number is in range")

This is equivalent to writing it out with and, but noticeably cleaner:

# The long-hand equivalent
if 10 <= number and number <= 20:
    print("Number is in range")

Both produce identical behavior, but the chained version reads almost exactly like the mathematical notation you'd write by hand, and it's the idiomatic way to express a range check in Python.

Practical use cases

Chained comparisons show up constantly in validation logic:

age = 25
if 18 <= age <= 65:
    print("Eligible")

score = 87
if 90 <= score <= 100:
    grade = "A"
elif 80 <= score <= 89:
    grade = "B"
else:
    grade = "C or below"

== vs. is: A Common Point of Confusion

This is the distinction that trips up more people than any other comparison-related topic in Python, and it's worth slowing down for.

Value equality vs. object identity

== checks whether two values are equal. is checks whether two variables refer to the exact same object in memory — identity, not equivalence.

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)   # True  — same values
print(a is b)   # False — two separate list objects, even though they look identical

a and b hold lists that look the same, but they're two distinct objects sitting at different locations in memory. == correctly reports they're equal in value; is correctly reports they're not the same object.

The integer caching gotcha

Here's a detail that genuinely surprises people, including intermediate developers: for performance reasons, CPython (the standard Python implementation) caches and reuses small integers, roughly in the range of -5 to 256. This means small integers can appear to pass an is check even without you intending an identity comparison:

a = 256
b = 256
print(a is b)   # True — small integers are cached and reused

x = 257
y = 257
print(x is y)   # False — outside the cached range, these are separate objects

This isn't something you should ever rely on intentionally — it's an internal implementation detail of CPython, not a guaranteed language feature, and it can behave differently in other Python implementations or even different circumstances within CPython itself. It's worth knowing about mainly so that if you ever see is unexpectedly return True for two integers, you understand why, rather than assuming your code is doing something it isn't.

Best practice

The rule to actually follow: use == for comparing values, which is the overwhelming majority of comparisons you'll ever write. Reserve is specifically for singleton checks — most notably, checking against None:

if x is None:      # correct — None is a singleton
    print("x has no value")

if x == 5:          # correct — comparing an actual value
    print("x is five")

Using is for general value comparisons (especially with numbers, strings, or lists) is a common source of subtle bugs precisely because of quirks like the integer caching behavior above — the code might happen to work today, on this particular Python implementation, and then silently break somewhere else.

PREVIOUSNEXT LESSON