How to Use the Python NOT EQUAL operator

Posted in Python by Dirk - last update: Dec 19, 2023

In Python, the “not equal” operator is represented by !=. You can use it to compare two values and check if they are not equal. You can use the != operator with various data types, including numbers, strings, and other objects. It compares the values on both sides of the operator and returns True if they are not equal, and False if they are equal.

Here’s a simple example:

a = 5
b = 10

if a != b:
    print("a is not equal to b")
else:
    print("a is equal to b")

Output:

a is not equal to b

Different data types

When using the “not equal” operator (!=) in Python with different data types, Python will still attempt to perform the comparison. Whether the comparison makes sense or not depends on the specific data types involved.

This can lead to unexpected results as shown in the example below:

a = 5
b = "5"

if a != b:
    print("a is not equal to b")
else:
    print("a is equal to b")
a is not equal to b

Even though a and b have different data types (integer and string), Python will still attempt the comparison. In this specific example, the condition will be true, and the message “a is not equal to b” will be printed. This is because the values are different, even if their types are different.

If the types are not compatible or cannot be sensibly compared, Python can raise a TypeError

Alternative: not

In Python, not is an alternative way to express inequality when used in combination with the == equality operator. Here’s an example:

a = 5
b = 10

# Using the not operator with the equality operator
if not (a == b):
    print("a is not equal to b")
else:
    print("a is equal to b")

In this example, the not operator is used to negate the result of the equality comparison (a == b). If a is not equal to b, the condition becomes True, and “a is not equal to b” will be printed.

While != is the dedicated “not equal” operator in Python, you can use the not operator with == to achieve the same result. However, it’s more common and idiomatic to use != for inequality comparisons. The not operator is more commonly used for negating boolean values or expressions.

References:

Other articles