Does '!=' equivelent to 'is not'
johnjsal at gmailNOSPAM.com
Tue Jun 17 05:40:14 CEST 2008
> I'm a bit confusing about whether "is not" equivelent to "!="
> if a != b:
> if a is not b:
> What's the difference between "is not" and "!=" or they are the same thing?
No, they are not the same thing. == and != test to see if the *value* of
two variables are the same. Like so:
>>> a = 'hello world'
>>> b = 'hello world'
>>> a == b
a and b both have the value of 'hello world', so they are equal
is and is not, however, do not test for value equivalence, they test for
object identity. In other words, they test to see if the object the two
variables reference are the same object in memory, like so:
>>> a is b
a and b are assigned to two different objects that happen to have the
same value, but nevertheless there are two separate 'hello world'
objects in memory, and therefore you cannot say that a *is* b
Now look at this:
>>> c = d = 'hello world'
>>> c == d
>>> c is d
In this case, they are again the same value, but now the is test also
shows that they are the same *object* as well, because both c and d
refer to the same 'hello world' object in memory. There is only one this
!= and is not work the same:
>>> a != b
>>> a is not b
>>> c != d
>>> c is not d
Hope that helps!
More information about the Python-list