# Python Comparison Operators: ==, !=, , =

Source: https://devdocs10.com/articles/python/python-comparison-operators  
By Murat Bo · Published 2026-11-05 · DevDocs10 (https://devdocs10.com)

Python comparison operators test how two values relate to each other. They return `True` or `False`, which you use in `if` statements, loops, filtering, and many other decisions. This article shows how each operator works, how Python compares different kinds of values, and the mistakes that often confuse beginners.

> **Difficulty:** Beginner
>
> **Helpful to know first:** basic Python variables, booleans, and how `if` statements work.

## How Python Comparison Operators Test Values

Comparison operators ask a yes-or-no question about two values. The answer is always a boolean: `True` if the relationship is correct, or `False` if it is not.

Here are the six comparison operators in Python:

- `==` means “equal to”
- `!=` means “not equal to”
- `<` means “less than”
- `>` means “greater than”
- `<=` means “less than or equal to”
- `>=` means “greater than or equal to”

These operators compare values, not variable names. If two variables hold the same value, the comparison is true even if they are different variables.

```python
age = 18
is_adult = age >= 18

print(is_adult)  # Output: True
```

The expression `age >= 18` becomes `True` because 18 is equal to 18. Python stores that result in `is_adult`.

## Comparing Numbers, Strings, and Booleans

Comparison operators work on many Python types, but the meaning depends on the type. Numbers are compared by numeric value, strings are compared lexicographically, and booleans behave like integers in many comparisons because `False` is treated like 0 and `True` is treated like 1.

### Comparing numbers

Number comparisons are the most direct. Python checks whether one number is bigger, smaller, or equal to another number.

```python
print(7 < 10)   # Output: True
print(3.5 >= 3) # Output: True
print(4 == 4.0)  # Output: True
```

Python compares `4` and `4.0` by value, so they are equal even though one is an `int` and the other is a `float`.

### Comparing strings

Strings are compared in alphabetical order based on Unicode code points, not by dictionary meaning. That is why uppercase and lowercase letters can produce surprising results.

```python
print("apple" < "banana")  # Output: True
print("Z" < "a")            # Output: True
print("cat" == "cat")       # Output: True
```

The second result may surprise you: `"Z"` comes before `"a"` in Unicode order. If you need human-friendly ordering, you usually sort after normalizing case, not with a direct comparison alone.

### Comparing booleans

Booleans are valid operands, but they are usually best treated as true/false flags rather than numbers. Still, the numeric relationship exists.

```python
print(True == 1)   # Output: True
print(False < True) # Output: True
```

This works because Python treats `False` as 0 and `True` as 1 for numeric comparison. Even so, writing code that depends on that habit is usually less clear than using actual booleans.

## How Chained Comparisons Work in Python

Python lets you write multiple comparisons in a single expression, such as `0 < age < 18`. This is not just shorthand for two separate comparisons; Python evaluates it as a chain and stops as soon as one part is false.

```python
age = 16

print(0 < age < 18)  # Output: True
print(18 <= age < 65) # Output: False
```

Chained comparisons read naturally and avoid repeating the same variable. They are common in range checks, validation, and guard conditions.

> Python evaluates a chained comparison like `a < b < c` as a single combined test, not as two unrelated expressions joined by `and`.

## When Comparison Operators Return True or False

Comparison operators do not change data. They produce a result. That result can be stored in a variable, used in a conditional, or printed directly.

```python
temperature = 29

if temperature >= 30:
    print("Hot")
else:
    print("Not hot")  # Output: Not hot
```

In a real program, comparison operators often act as the condition that chooses one branch or another. That is why they are one of the most important parts of control flow.

## Comparing Objects, Lists, and Other Containers

Comparison operators also work with some containers such as lists and tuples. Equality compares content, while ordering comparisons depend on the type and are not always meaningful.

### Equality compares content

Two lists are equal if they contain the same items in the same order.

```python
print([1, 2, 3] == [1, 2, 3])  # Output: True
print([1, 2] != [1, 2, 3]) # Output: True
```

This is useful when you want to check whether two collections represent the same data.

### Identity is a different idea

Many beginners confuse `==` with `is`. They are not the same. `==` compares values, while `is` checks whether two variables refer to the same object in memory.

```python
a = [1, 2]
b = [1, 2]

print(a == b)  # Output: True
print(a is b) # Output: False
```

The two lists hold the same values, so `==` is true. But they are separate list objects, so `is` is false.

## Why Python Sometimes Compares More Than You Expect

Comparison operators usually seem simple, but a few details matter in real programs. These are the places where beginners most often get surprising results.

### Python does not compare by “alphabetical meaning”

String comparison is based on Unicode order, not on human language rules. That means punctuation, capitalization, and accents can affect the result.

```python
print("Zoo" < "apple")  # Output: True
```

That result happens because uppercase letters have smaller code points than lowercase letters. If you are sorting user-visible text, normalize it first or use a locale-aware approach when appropriate.

### Comparison operators do not coerce unrelated types

Python 3 does not automatically convert arbitrary unrelated types so they can be compared. Some comparisons work only when the types have a defined ordering or shared meaning.

```bash
# This is fine in Python 3:
print(3 == "3")  # Output: False

# But ordering different unrelated types usually fails:
# print(3 < "3")
```

Equality between different types usually gives `False`. Ordering between unrelated types is not something you should rely on.

### Floating-point comparisons can be tricky

Numbers that look simple on paper may not be stored exactly in binary floating-point form. This matters when you compare decimals that come from calculations.

```python
total = 0.1 + 0.2

print(total == 0.3)  # Output: False
```

That does not mean Python is broken. It means floating-point arithmetic stores an approximation, so exact equality is sometimes the wrong test. Use a tolerance when you need numeric closeness instead of perfect equality.

> For decimal-heavy work like money, use the standard library `decimal` module instead of comparing floats directly.

## Predict the Output

Each of these snippets checks a common misunderstanding. Read the code first, then decide what gets printed.

### Chained comparison versus separate comparisons

```python
x = 5
print(1 < x < 10)
print(1 < x and x < 10)
```

What does this print?

**Answer:**

It prints two lines:

```bash
# Output:
True
True
```

The first line uses a chained comparison, which checks that 1 is less than 5 and 5 is less than 10. The second line uses `and`, which combines two boolean expressions. In this case, both expressions are true, so the result is also true.

### Equality of values versus identity of objects

```python
a = [1, 2]
b = a
b.append(3)
print(a == b)
```

What does this print?

**Answer:**

It prints:

```bash
# Output:
True
```

a and b refer to the same list object. Appending through b changes that one list, so both names see the same content. Since the contents are equal, `a == b` is true.

## Common Mistakes with Python Comparison Operators

### Using one equals sign instead of two

Beginners often write `=` when they mean comparison. In Python, `=` assigns a value, while `==` compares values.

**Problem:** This code tries to compare `age`, but `=` is assignment, not comparison, so Python raises a syntax error.

```python
age = 18

if age = 18:
    print("Adult")
```

**Fix:** Use `==` when you want to test equality.

```python
age = 18

if age == 18:
    print("Adult")
```

The corrected version works because `==` is the comparison operator Python expects inside the condition.

### Using is to compare values instead of objects

`is` checks object identity, not value equality. It can appear to work with small integers or interned strings, which makes the mistake harder to notice.

**Problem:** This code asks whether two strings have the same content, but `is` checks whether they are the same object in memory.

```python
name1 = "py" + "thon"
name2 = "python"

if name1 is name2:
    print("Same text")
```

**Fix:** Use `==` to compare text content.

```python
name1 = "py" + "thon"
name2 = "python"

if name1 == name2:
    print("Same text")
```

The fixed version works because both strings contain the same characters, which is what you want to test.

### Comparing floats for exact equality after arithmetic

Floating-point rounding can make a value look exact when it is not. That can break equality checks after calculations.

**Problem:** This code expects the sum to be exactly 0.3, but binary floating-point rounding makes the comparison false.

```python
total = 0.1 + 0.2

if total == 0.3:
    print("Equal")
```

**Fix:** Compare with a tolerance when you are working with floats from arithmetic.

```python
from math import isclose

total = 0.1 + 0.2

if isclose(total, 0.3):
    print("Equal")
```

The corrected version works because `isclose()` checks whether the numbers are close enough for practical use.

## Find the Bug

Here is a small program that looks reasonable, but it has a subtle logic bug about comparison. Find it before you read the answer.

```python
def is_valid_score(score):
    if 0 <= score <= 100:
        return True
    return False

print(is_valid_score(100))  # expected: True
print(is_valid_score(-1))   # expected: False
```

**Answer:**

The bug is not in the chained comparison itself. The real problem is that this function is more verbose than it needs to be, and that often hides the fact that the second `return False` is unnecessary. The bigger lesson is to trust the comparison to produce a boolean directly.

**Fixed code:**

```python
def is_valid_score(score):
    return 0 <= score <= 100

print(is_valid_score(100))  # Output: True
print(is_valid_score(-1))   # Output: False
```

The corrected version works because the comparison already evaluates to `True` or `False`, so returning it directly is clearer.

## When to Use Comparison Operators and When to Use Something Else

Comparison operators are the right tool when you need to test a relationship between values. But sometimes another operator or function is a better fit.

| Task | Use this | Why |
| --- | --- | --- |
| Check whether two values are equal | `==` | Compares values directly |
| Check whether two names refer to the same object | `is` | Tests identity, not value |
| Check whether a number is inside a range | `<=` or chained comparisons | Clear and readable |
| Check whether a value is close to a float | `math.isclose()` | Handles rounding error |
| Check whether an item appears in a collection | `in` | Membership is different from comparison |

Use comparison operators for direct questions like “Is this greater than that?” or “Are these values equal?” Use other tools when you are checking identity, membership, or approximate numeric equality.

## Interview Questions About Python Comparison Operators

### What is the difference between `==` and `is`?

`==` compares values. `is` compares object identity. Two separate lists with the same items are usually equal with `==` but not identical with `is`.

### Why does `0.1 + 0.2 == 0.3` return false?

Because floating-point numbers are stored in binary approximations. The result of the addition is very close to 0.3 but not exactly equal, so direct equality fails.

### How does Python handle chained comparisons like `a < b < c`?

Python evaluates them as a chain, so it checks both relationships in one expression. This is clearer than writing `a < b and b < c`, and it avoids repeating the middle value.

## Try It Yourself

Write a small program that checks whether a grade is in the passing range.

- Create a variable named `grade` and give it the value `72`.
- Print `"Pass"` if the grade is between 60 and 100, inclusive.
- Otherwise print `"Fail"`.
- Use a chained comparison in the condition.

**Expected output:**

```python
Pass
```

**Hint:** The condition should look like `60 <= grade <= 100`.

**Solution:**

```python
grade = 72

if 60 <= grade <= 100:
    print("Pass")
else:
    print("Fail")
```

## Summary

- Python comparison operators return booleans: `True` or `False`.
- `==` compares values, while `is` compares object identity.
- Chained comparisons like `0 < x < 10` are valid and readable.
- String comparison uses Unicode order, not human-friendly alphabetical rules.
- Float equality can fail after arithmetic because of rounding.
- Use `math.isclose()` when you need approximate numeric equality.

Next, learn Python logical operators such as `and`, `or`, and `not`, which combine comparison results into larger conditions.
