Latest Code Tutorials

Python Not Equal Operator Example | Not Equal Operator In Python


Python Not Equal Operator Example is today’s topic. Python is dynamic and strongly typed language, so if the two variables have the same values, but they are of a different type, then not equal operator will return True. For comparing object identities, you can use the keyword is, and its negation is not.

Python Not Equal Operator

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

print(1 == 1)
print(1 != 1)
print([] is [])

See the output.

➜  pyt python3
➜  pyt

See the following table.

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


There’s the != (not equal) operator that returns True when two values differ, though be careful with the types because “1 != 1”. This will always return True and “1” == 1 will always return False since the types differ. Python is dynamically, but strongly typed, and other statically typed languages would complain about comparing different types.

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


x = 11
y = 21
z = 19

print(f'x is not equal to y = {x!=y}')

flag = x != z
print(f'x is not equal to z = {flag}')

# python is strongly typed language
s = '11'
print(f'x is not equal to s = {x!=s}')

See the output.

➜  pyt python3
x is not equal to y = True
x is not equal to z = True
x is not equal to s = True
➜  pyt

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 want to compare it for record value. We can achieve this by implementing our __ne__() function.

See the following code.


class App:
    id = 0
    netflix = ''

    def __init__(self, i, s): = i = s

    def __ne__(self, other):
        # return true if different types
        if type(other) != type(self):
            return True
        if !=
            return True
            return False

d1 = App(1, 'Stranger Things')
d2 = App(2, 'Money Heist')
d3 = App(3, 'Sacred Games')

print(d1 != d2)
print(d2 != d3)

See the output.

➜  pyt python3
➜  pyt

Finally, Python Not Equal Operator Example is over.

Recommended Posts

Null Object In Python Example

Python property() Example

Python pow() Example

Python open() Example

Python iter() Example

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.