Python Not Equal Operator (!=): A Complete Guide (with Examples)

Comparing values in code is one of the essential tasks you need to do all the time. In Python, there are six comparison operators in total. One of them, the not equal operator (!=) is the one you can use to check if a value doesn’t equal another.

For instance:

1 != 2 # Returns False

This is a comprehensive guide to the not-equal operator in Python. You will also see how to make custom objects support comparisons of type “not equal”.

How Does the Not Equal Operator Work in Python

Not equal operator in python comparing 1 and 2.

Python has a total of six built-in comparison operators. In case you’re not familiar with those yet, here’s a quick recap:

Operator Name
> Less than
< Greater than
>= Less than or equal
<= Greater than or equal
== Equal
!= Not equal

In this guide, you will focus on the not-equal operator !=.

The not-equal operator != checks if two values are not equal. It returns True if the values are not equal and False if they are.

Here are some example comparisons between different types of objects in Python:

1 != 2              # True
1 != 1              # False

[1, 2] != [2, 1]    # True
(1, 2) != (2, 1)    # True  

"Test" != "Banana"  # True

Now you have a basic understanding of how the not-equal comparison operator works.

Next, let’s have a look at how the not equal operator is different in Python 2.

The Old-School Not Equal Operator ‘<>’ in Python 2

The oldschool way to check unequality was by using the <> operator in Python 2

In Python 2 there you can use the <> operator to check if two values are not equal to one another.

Example use in Python 2:

>>> 1 <> 2
True

>>>1 <> 1
False

But this is just to show you that such an operator once existed. In Python 3, this operator is removed, and using it causes a syntax error. Thus, it doesn’t make sense to use such an operator anymore.

>>> 1 <> 2
  File "<stdin>", line 1
    1 <> 2
       ^
SyntaxError: invalid syntax

Now you understand how the not equal operator works in Python, how to use it, and how it was used back in the day.

Finally, let’s take a look at an advanced topic about supporting not equal operators with custom objects.

Advanced Comparison with Not Equal in Python

So far you have only seen what the not-equal operator call looks like and what it returns as a result.

But as it turns out, there is a special method called __ne__() behind the scenes that makes not equal comparisons possible.

The __ne__() Method in Python

The __ne__ method called on 1 and 2 to check if they are not equal
This code is equivalent to 1 != 2. Try it!

When you call not equal (!=) on two numbers in Python, you are calling a special method called __ne__() under the hood. This special method defines what happens when you call not equal on two objects.

For example, comparing two integers with != is possible because Python’s int type implements the __ne__() method behind the scenes.

To verify this, you can check the results of the following calls:

>>> 1 != 2
True

>>> (1).__ne__(2)
True

In this piece of code, the first call automatically gets turned into the second call. So these two produce an identical result.

Alternatively, you can verify that the int type really implements __ne__() by checking the attributes of the int class. This is possible using the dir() function:

>>> dir(int)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

As you can see from the ocean of attributes, one of them is called ‘__ne__’. This verifies that the int class implements __ne__() method to support not the equal operator on integer objects.

Override the __ne__() Method in Python

In Python, you can override special methods. This means you can provide an implementation of the __ne__() method in your class. This is to support the not-equal operator between custom objects.

For example, if you have a Fruit class, you can decide what happens when you call fruit1 != fruit2 by implementing the __ne__() method.

Before customizing the __ne__() method, it is important to notice that usually, you want to override all the other comparison methods too. This is because it can be confusing if your objects for example support obj1 != obj2, but not obj1 == obj2.

Here is a list of all the special methods you need to implement to support object comparison:

__eq__ Equal
__ne__ Not equal
__lt__ Less than
__gt__ Greater than
__le__ Less than or equal
__ge__ Greater than or equal

To keep it short, we are not going to implement all of these methods in this guide.

Now, let’s take a look at an example where we write a custom __ne__() operator into a custom class

Here is an example of a Fruit class that has a customized way to compare if two objects are not equal by comparing the weights of the fruits:

class Fruit:
    # Initialize a fruit with name and weight
    def __init__(self, name, weight):
        self.name = name
        self.weight = weight

    # When two fruit objects are compared with !=, this method is called.
    # In this case, it only cares about the weights of the objects.
    def __ne__(self, other):
        return self.weight != other.weight


# Let's create two fruits with the same mass but with different names.
banana = Fruit("Banana", 0.2)
pineapple = Fruit("Pineapple", 0.2)

print(banana != pineapple)

Output:

False

Customizing or overriding a special method in Python is called operator overloading. To learn more about operator overloading, check out this article.

Conclusion

Today you learned how to use the not equal operator in Python to check if a value is not equal to another.

To recap, the not equal operator is applied between two types supporting comparison. It returns True if the values are not equal and False if they are.

Here is an example use of the not equal operator:

1 != 2

In addition to learning how to use the not equal operator, you learned how to support it in a custom class. This is possible by overriding the __ne__() method in the class. This method describes what happens when applying != on its objects.

Thanks for reading. I hope you find it useful. Happy coding!

Further Reading