What is difference in Python operators != and "is not"?

PythonServer Side ProgrammingProgramming

In Python != is defined as not equal to operator. It returns true if operands on either side are not eual to each other, and returns false if they are equal.

>>> (10+2) != 12                # both expressions are same hence false
False
>>> (10+2)==12                
True
>>> 'computer' != "computer"     # both strings are equal(single and double quotes same)
False
>>> 'computer' != "COMPUTER"   #upper and lower case strings differ
True

Whereas is not operator checks whether id() of two objects is same or not. If same, it returns false and if not same, it returns true

>>> a=10
>>> b=a
>>> id(a), id(b)
(490067904, 490067904)
>>> a is not b
False
>>> a=10
>>> b=20
>>> id(a), id(b)
(490067904, 490068064)
>>> a is not b
True
raja
Published on 13-Feb-2018 09:30:22
Advertisements