Python
programming
not equal operator
syntax
code comparison

Is there a not equal operator in Python?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Yes, Python has a not-equal operator: !=. It is the standard and only modern inequality operator in Python 3. You will use it constantly in conditionals, filters, validation rules, and comparisons between custom objects.

Some legacy references mention <>, but that syntax belonged to older Python versions and is invalid in Python 3. If you maintain old code or copy examples from outdated sources, this difference is often the first source of confusion.

Core Sections

1. Basic inequality checks with !=

!= returns True when values are different and False otherwise.

python
print(5 != 3)          # True
print("cat" != "cat")  # False
print([1, 2] != [1, 3]) # True

It works across built-in types that define equality behavior. Use it directly in control flow:

python
status = "failed"
if status != "ok":
    print("Handle error path")

For Python 2 compatibility notes, <> existed but should be removed during migration.

2. How != behaves with custom classes

For user-defined classes, inequality depends on equality methods (__eq__ and __ne__). In Python 3, if __ne__ is not defined, Python may infer it from __eq__.

python
1class User:
2    def __init__(self, user_id: int):
3        self.user_id = user_id
4
5    def __eq__(self, other):
6        if not isinstance(other, User):
7            return NotImplemented
8        return self.user_id == other.user_id
9
10u1 = User(1)
11u2 = User(2)
12print(u1 != u2)  # True

If equality is not implemented, object identity rules apply, which may not match your domain expectations.

3. Common comparison patterns and safer alternatives

Use inequality for value comparison, and identity operators (is / is not) only for singleton checks (None, True, False, sentinel objects).

python
1value = None
2
3# Preferred
4if value is not None:
5    print("Has value")
6
7# Avoid
8if value != None:  # less idiomatic
9    pass

For floating-point values, exact inequality can be misleading due to representation error. Prefer tolerance-based checks.

python
1import math
2
3x = 0.1 + 0.2
4print(x != 0.3)  # often True
5print(not math.isclose(x, 0.3, rel_tol=1e-9))

Use the right comparison tool for the data type and domain.

Common Pitfalls

  • Using <> in Python 3 code, which causes a syntax error.
  • Confusing != (value inequality) with is not (identity inequality).
  • Comparing floats with exact inequality where tolerance comparison is required.
  • Forgetting to implement meaningful equality for custom classes, leading to identity-based results.
  • Using != None in style-sensitive codebases where is not None is the expected pattern.

Summary

Python’s not-equal operator is !=, and it is the correct choice for value inequality in Python 3. Use it directly for normal comparisons, pair it with proper equality methods in custom classes, and use is not None or tolerance checks where semantics demand it. Clear comparison intent prevents subtle logic bugs.

When working with libraries like NumPy or pandas, inequality can behave element-wise instead of producing a single boolean. That is often desired, but control-flow code should avoid using array-like inequality directly in if conditions. For DataFrames and arrays, generate masks explicitly and then reduce (any, all) according to business rules. This keeps semantics explicit and avoids ambiguous truth-value errors.

Code reviews should also check comparison clarity for domain entities. If equality semantics are custom (for example compare by id only), document that contract in class definitions and tests. Otherwise, changing one comparison method can cascade into subtle bugs in deduplication, caching, and authorization checks.

Clear comparison semantics are especially important in security-sensitive checks, where confusing identity and equality can create authorization flaws.

Small comparison mistakes are easy to miss in tests, so linting and explicit style conventions around equality operators are worth adopting.

Make inequality intent explicit in code comments when domain rules are non-obvious.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.