Does '!=' equivelent to 'is not'

John Salerno johnjsal at gmailNOSPAM.com
Mon Jun 16 23:40:14 EDT 2008


pirata wrote:
> 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
True

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
False

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
True
 >>> c is d
True

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 
time.

!= and is not work the same:

 >>> a != b
False
 >>> a is not b
True
 >>> c != d
False
 >>> c is not d
False
 >>>

Hope that helps!



More information about the Python-list mailing list