2f_zlw

Python is vs ==

Use is to compare int and int, string and string. Use == to compare other types.
1 is 1 #True
"python" is "python" #True
[] == [] #True
{} is {} #False

Sign in or sign up to add your response.

2 Responses

1261
Ce25469ae339c0d8f3a8266bf40c9083

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 "=="

over 1 year ago ·
19846
F0b6f866844ff936e78c1a3ec6b5f02c
>>> a = 500
>>> b = a
>>> c = 500
>>> help(id)
Help on built-in function id in module __builtin__:

id(...)
    id(object) -> integer

    Return the identity of an object.  This is guaranteed to be unique among
    simultaneously existing objects.  (Hint: it's the object's memory address.)

>>> id(a)
33024604
>>> id(b)
33024604
>>> id(c)
33024628
>>>
>>> a == b
True
>>> a is b
True
>>> a == c
True
>>> a is c
False
>>>
over 1 year ago ·
Featured Programming Job

Software Developer / Bioinformatician
·
Heidelberg, Germany
·
Full Time
Search all programming jobs