Learn Python
>>> operators.op_comparison

Comparison Operators in Python

#concept

Comparison operators compare two values and always produce a boolean result. Python has six: == (equal), != (not equal), < (less than), > (greater than), <= (less than or equal), and >= (greater than or equal). They work on numbers, and also on strings, which are compared alphabetically.

#how it works
1

== checks equality

Different from = (assignment) — one of the most common beginner mix-ups.

2

!= checks inequality

True whenever the two values differ.

3

<, >, <=, >= compare order

Numerically for numbers, alphabetically (character by character) for strings.

4

Comparisons can be chained

1 < x < 10 checks both conditions in a single, natural-reading expression.

5

Comparing unrelated types

== simply returns False rather than erroring; ordering comparisons like < raise a TypeError instead of guessing.

#example
print(5 == 5)
print(5 != 3)
print("apple" < "banana")
print(1 < 5 < 10)
Output
True
True
True
True
1== compares values for equality — 5 == 5 is True.
2!= is the opposite of == — 5 != 3 is True since they differ.
3"apple" < "banana" compares strings alphabetically, character by character, the same way a dictionary orders words.
41 < 5 < 10 is a chained comparison — Python checks 1 < 5 and 5 < 10 together, and both must be True for the whole expression to be True.
#variants

Equality (==) vs Assignment (=)

One of the most common beginner mix-ups — = assigns a value, == checks whether two values are equal.

x = 5
print(x == 5)
Output
True

Chained Comparisons

Python lets you chain comparisons naturally, unlike many other languages.

age = 25
print(18 <= age <= 65)
Output
True
#use cases
Writing conditions for if statements and while loops
Validating that user input falls within an expected range
Sorting algorithms, which rely entirely on comparison operators to decide order
Filtering data — keeping only the items that satisfy a comparison

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.