Is there a "not equal" operator in Python?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping
--
Chapters
00:00 Question
00:25 Accepted answer (Score 680)
00:47 Answer 2 (Score 70)
01:10 Answer 3 (Score 32)
02:09 Answer 4 (Score 13)
02:25 Thank you
--
Full question
https://stackoverflow.com/questions/1106...
Accepted answer links:
[comparison operators]: https://docs.python.org/3/library/stdtyp...
Answer 2 links:
[Python - Basic Operators]: http://www.tutorialspoint.com/python/pyt...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #operators
#avk47
ACCEPTED ANSWER
Score 693
Use !=. See comparison operators. For comparing object identities, you can use the keyword is and its negation is not.
e.g.
1 == 1 # -> True
1 != 1 # -> False
[] is [] #-> False (distinct objects)
a = b = []; a is b # -> True (same object)
ANSWER 2
Score 73
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.
ANSWER 3
Score 32
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 values
print a is b # This will print False since they are different objects.
ANSWER 4
Score 8
Seeing as everyone else has already listed most of the other ways to say not equal I will just add:
if not (1) == (1): # This will eval true then false
# (ie: 1 == 1 is true but the opposite(not) is false)
print "the world is ending" # This will only run on a if true
elif (1+1) != (2): #second if
print "the world is ending"
# This will only run if the first if is false and the second if is true
else: # this will only run if the if both if's are false
print "you are good for another day"
in this case it is simple switching the check of positive == (true) to negative and vise versa...