When to use == and when to use is?

They are fundamentally different.

  1. == compares by calling the __eq__ method
  2. is returns true if and only if the two references are to the same object

So in comparision with say Java:

  1. is is the same as == for objects
  2. == is the same as equals for objects

As far as I can tell, is checks for object identity equivalence. As there's no compulsory "string interning", two strings that just happen to have the same characters in sequence are, typically, not the same string object.

When you extract a substring from a string (or, really, any subsequence from a sequence), you will end up with two different objects, containing the same value(s).

So, use is when and only when you are comparing object identities. Use == when comparing values.


Simple rule for determining if to use is or == in Python

Here is an easy rule (unless you want to go to theory in Python interpreter or building frameworks doing funny things with Python objects):

Use is only for None comparison.

if foo is None

Otherwise use ==.

if x == 3

Then you are on the safe side. The rationale for this is already explained int the above comments. Don't use is if you are not 100% sure why to do it.