Skip to content Skip to sidebar Skip to footer

Python: Difference Between != And "is Not"

I'm unclear about the difference between the syntax != and is not. They appear to do the same thing: >>> s = 'a' >>> s != 'a' False >>> s is not 'a' Fal

Solution 1:

is tests for object identity, but == tests for object value equality:

In [1]: a =3424In [2]: b =3424In [3]: a is b
Out[3]: FalseIn [4]: a == b
Out[4]: True

Solution 2:

is not compares references. == compares values

Solution 3:

Depending on how you were confused, this might help.

These statements are the same:

[cforcin s ifc!='o'][cforcin s if not c=='o']

Solution 4:

I'd like to add that they definitely do not do the same thing. I would use !=. For instance if you have a unicode string....

a = u'hello''hello'isnot a
True'hello' != a
False

With !=, Python basically performs an implicit conversion from str() to unicode() and compares them, whereas with is not, it matches if it is exactly the same instance.

Solution 5:

I am just quoting from reference, is tests whether operands are one and same, probably referring to the same object. where as != tests for the value.

s = [1,2,3]
while s isnot []:
   s.pop(0);

this is a indefinite loop, because object s is never equal to an object reference by [], it refers to a completely different object. where as replacing the condition with s != [] will make the loop definite, because here we are comparing values, when all the values in s are pop'd out what remains is a empty list.

Post a Comment for "Python: Difference Between != And "is Not""