How to use Not Equal in Python

A not equal expression in Python will return True if the two values supplied are not the same and False if they are. In Python, the not equal operator is != (exclamation followed by equal character) and is placed between the two values to evaluate.

 

Let's look at some examples to demonstrate how this works.

 

Assign Not Equal Result to a Variable

In the example below, we will assign the result from a not equal expression to a variable.

 

result = 1 != 0

print(result)
True

 

The two values are not equal so the result is True.

 

Not Equal to in an if Statement

Here is another example using a not equal expression inside an if-else statement:

 

if 1 != 0:
   print(True)
else:
   print(False)
False

 

Not Equal with Ternary Operator

Here is another example demonstrating the use of != within a Python ternary expression:

 

result = 'No match' if 1 != 0 else 'Match'

print(result)
No match