Difference between 'is not' and '!=' ?

Chris Rebert clp2 at rebertia.com
Mon May 10 19:31:54 EDT 2010


On Mon, May 10, 2010 at 4:25 PM, AON LAZIO <aonlazio at gmail.com> wrote:
> As subject says, what is the differences of 'is not' and '!='. Confusing..

!= checks value inequality, `is not` checks object identity /
"pointer" inequality
Unless you're doing `foo is not None`, you almost always want !=.

By way of demonstration (using the non-negated versions to be less confusing):
>>> x = [1, 2]
>>> y = [1, 2]
>>> x == y
True
>>> x is y
False
>>> z = x
>>> x is z
True
>>> z is y
False
>>> x.append(3)
>>> x
[1, 2, 3]
>>> y
[1, 2]
>>> z
[1, 2, 3]
>>> x is z
True

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list