Explain Codes LogoExplain Codes Logo

Is there a "not equal" operator in Python?

python
functions
best-practices
dataframe
Anton ShumikhinbyAnton Shumikhin·Feb 25, 2025
TLDR

The Python "not equal" operator is !=. It checks the inequality and evaluates to True if operands are dissimilar.

For instance:

result = (3 != 4) # True; because 3 and 4 have a 'not-so-equal' relationship

Breaking down "not equal"

The != operator compares the values of two operands and returns True if they don't match. It's like the operator's version of a disagreement.

print(2 != 2) # False; well, two 2's can't disagree; they're pretty much the same!

Comparing Identity: 'is not'

In Python, is not checks for object identity, meaning it verifies if they are the same object, not just identical twins.

a = [1, 2, 3] b = [1, 2, 3] print(a == b) # True; values match print(a is not b) # True; they're twins, but not the same person...uh...object

The Plot Twist of Data Types

Beware, like in epic movie twists, != can throw surprises when you involve different data types. When in doubt, raise the curtain with explicit type conversion.

print('3' != 3) # True; a number and a numeric string walk into a bar...

The Art of Negation

Use not with == to simulate a "not equal" operation. It's kind of like a plot reversal in a mystery movie.

print(not (1 == 1)) # False; because 1 is not...oh wait, it is!

The relic: "<>"

Once upon a time, Python used <> as a "not equal" operator. Now, it's just a mythology for Python 3 folks. Stick with != to be a hit with modern Pythonistas.

The Full Picture

Using the right tool...uh...operator

Choosing the right operator is like picking the right cheese for your burger. != or is not, it depends on what you're comparing - values or identities.

Beware of the Mutable Beings

Mutable objects like lists or dictionaries have the power to change state. Don't get surprised if your comparisons yield unexpected results.

a = b = [1, 2] b.append(3) print(a != b) # False; they changed in unison, like synchronized swimmers

Emptiness and the Science of Falsiness

Emptiness is considered False in Python. When negating, you may get surprising results.

print(not []) # True; an empty list has the truth value of...a deserted island!

Make it readable, not a thriller

With complex conditions, it's always helpful to use parentheses. It's like shining a flashlight on a dark mystery.

print((not []) and (1 != 2)) # True; it's like solving a beautifully complex plot