开发者

Python: Difference between != and "is not" [duplicate]

This question already has answers here: Python 'is not' operator (4 answers) Closed 17 days ago.

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'
False

But, when I use is not in a list comprehension, it produces a different result than if I use !=.

>>> s = "hello"
>>> [c for c in s if c is not 'o']
['h', 'e', 'l', 'l', 'o']
>>> [c开发者_高级运维 for c in s if c != 'o']
['h', 'e', 'l', 'l']

Why did the o get included in the first list, but not the second list?


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

In [1]: a = 3424
In [2]: b = 3424

In [3]: a is b
Out[3]: False

In [4]: a == b
Out[4]: True


is not compares references. == compares values


Depending on how you were confused, this might help.

These statements are the same:

[c for c in s if c != 'o']
[c for c in s if not c == 'o']


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' is not 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.


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 is not []:
   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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜