Difference between 'is' and '=='

Fuzzyman fuzzyman at gmail.com
Mon Mar 27 07:22:01 EST 2006


mwql wrote:
> Hey guys, this maybe a stupid question, but I can't seem to find the
> result anywhere online. When is the right time to use 'is' and when
> should we use '=='?
>
> Thanks alot~

'==' is the equality operator. It is used to test if two objects are
'equal'.

'is' is the identity operator, it is used to test if two
names/references point to the same object.

a = {'a': 3}
b = {'a': 3}
a == b
True
a is b
False
c = a
a is c
True

The two dictionaries a and b are equal, but are separate objects.
(Under the hood, Python uses 'id' to determine identity).

When you bind another name 'c' to point to dictionary a, they *are* the
same object - so a *is* c.

One place the 'is' operator is commonly used is when testing for None.
You only ever have one instance of 'None', so

a is None

is quicker than

a == None

(It only needs to check identity not value.)

I hope that helps.

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml




More information about the Python-list mailing list