Should you use the != operator or the ‘is not’ statement when comparing values in Python? Read on to find out!
The != Comparison Operator
The != operator can be used to compare two variables or statements’ return values. If they are not equal, the statement will return TRUE.
Python is forgiving when it comes to comparing variables of different types. So if the type of the variables being compared is different, but the value is the same, it will return TRUE (rather than throwing an error) as they are not equal in both type and value.
myNumber = 4 myString = 'hello' if myNumber != 5: print('Number is not equal to 5') if (myNumber + 1) != (7 - 2): print('Number is not equal to 5') if myString != "hello" : print('String does not say hello')
As you can see above, values, variables, and statements, containing or returning different variable types can be used on either side of the != operator to test if they are not equal.
What About the <> Operator?
The <> is the lesser-seen brother of !=. It looks different, but it does the same thing! It’s rarely used as the concept of greater than and less than is quite specific to comparing numbers, so it doesn’t make sense to use it for other comparisons, even if it works.
The ‘is not’ Statement
The ‘is not’ statement does the exact same thing as the != operator. They are interchangeable.
myNumber = 4 myString = 'hello' if myNumber is not 5 : print('Number is not equal to 5') if (myNumber + 1) is not (7 - 2) : print('Number is not equal to 5') if myString is not "hello" : print('String does not say hello')
Use whichever one you want. They do the same thing and work regardless of the statements, operands, or variable types either side of them.
I’d stick to != for brevity and because it’s also commonly used for the same purpose in other programming languages.