Difference between 'is' and '=='

Diez B. Roggisch deets at nospam.web.de
Mon Mar 27 09:04:07 EST 2006


mwql wrote:

> It's really strange,
> 
> if
> a = 1
> b = 1
> a is b ==> True
> 
> the same thing applies for strings, but not for dict, lists or tuples
> I think the 'is' operator is useful for objects only, not for primitive
> types,
> I think I solved the mystery behind my bugged code =)

 The reason that "is" works for small numbers is that these are cached for
performance reasons. Try

>>> a = 1000000
>>> b = 1000000
>>> a is b
False

So - your conclusion is basically right: use is on (complex) objects, not on
numbers and strings and other built-ins. The exception from the rule is
None - that should only exist once, so

foo is not None

is considered better style than foo == None.

Diez



More information about the Python-list mailing list