Is there a "not equal" operator in Python? Is there a "not equal" operator in Python? python python

Is there a "not equal" operator in Python?


Use !=. See comparison operators. For comparing object identities, you can use the keyword is and its negation is not.

e.g.

1 == 1 #  -> True1 != 1 #  -> False[] is [] #-> False (distinct objects)a = b = []; a is b # -> True (same object)


Not equal != (vs equal ==)

Are you asking about something like this?

answer = 'hi'if answer == 'hi':     # equal   print "hi"elif answer != 'hi':   # not equal   print "no hi"

This Python - Basic Operators chart might be helpful.


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.

There's also the else clause:

# This will always print either "hi" or "no hi" unless something unforeseen happens.if hi == "hi":     # The variable hi is being compared to the string "hi", strings are immutable in Python, so you could use the 'is' operator.    print "hi"     # If indeed it is the string "hi" then print "hi"else:              # hi and "hi" are not the same    print "no hi"

The is operator is the object identity operator used to check if two objects in fact are the same:

a = [1, 2]b = [1, 2]print a == b # This will print True since they have the same valuesprint a is b # This will print False since they are different objects.