Joined November 2012
·

Dennis Brakhane

Hacker/CEO at inoio
·
Hamburg
·
·

Posted to Python is vs == over 1 year ago

That's not correct. "is" checks for identity, "==" for equality.

Only use "is" if you must know whether you are working on the same object; thus in practise, you only need to use it for "obj is None".

Your "int" and "string" examples only work by chance, due to the way the CPython interpreter is implemented. Take a look at this:

a = 100
b = 100
print a is b # True

a = 1000
b = 1000
print a is b # False

CPython caches instances of small integers, like 100. Therefore, they are the same object, larger integers however are created each time they are used, unless they are in the same operation or so (which is why "1000 is 1000" will still be True)

I do not know when and how CPython uses the same string instance for the same strings, but you should use == there as well. You could force instances of the same ("equal") string to be the same object by using intern, but you really shouldn't:

a = "python"
b = "pytho"
b += "n"
print a is b # False

a = intern(a)
b = intern(b)
print a is b # True

tl;dr: only use "is" when checking for None, otherwise, always use "=="

Achievements
17 Karma
0 Total ProTip Views