Python: Difference between: = and "is not"

I do not understand the difference between the syntax != And is not . They seem to do the same thing:

 >>> s = 'a' >>> s != 'a' False >>> s is not 'a' False 

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

 >>> 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 was o included in the first list, but not in the second list?

+7
source share
5 answers

is tests to identify the object, but == checks if the value of the object is equal:

 In [1]: a = 3424 In [2]: b = 3424 In [3]: a is b Out[3]: False In [4]: a == b Out[4]: True 
+19
source

is not compares links. == compares values

+6
source

Depending on how embarrassed you are, this may help.

These statements are the same:

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

I just quote from the link, is checks if the operands are the same, possibly referring to the same object. where != checks the value.

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

this is an undefined loop, because the object s is never equal to the reference to the object [], this refers to a completely different object. where, replacing the condition with s != [] , make the loop defined, because here we compare the values ​​when all the values ​​from s crowd out what remains, this is an empty list.

0
source

I would like to add that they definitely do not do the same. I would use! =. For example, if you have a string in Unicode ....

 a = u'hello' 'hello' is not a True 'hello' != a False 

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

-one
source

All Articles