Python not equal operator with Example

Python not equal operator returns True if two variables are of same type and have different values, if the values are same then it returns False.

Python is dynamic and strongly typed language, so if the two variables have the same values but they are of different type, then not equal operator will return True.

Python not equal operators

Operator Description
!= Not Equal operator, works in both Python 2 and Python 3.
<> Not equal operator in Python 2, deprecated in Python 3.

Python 2 Example

Let’s see some examples of not-equal operator in Python 2.7.

Python 3 Example

Here is some examples with Python 3 console.

We can use Python not equal operator with f-strings too if you are using Python 3.6 or higher version.

Output:

Python not equal with custom object

When we use not equal operator, it calls __ne__(self, other) function. So we can define our custom implementation for an object and alter the natural output.

Let’s say we have Data class with fields – id and record. When we are using the not-equal operator, we just want to compare it for record value. We can achieve this by implementing our own __ne__() function.

Output:

Notice that d1 and d2 record values are same but “id” is different. If we remove __ne__() function, then the output will be like this:

You can checkout complete python script and more Python examples from our GitHub Repository.

By admin

Leave a Reply