Where developers come to connect, share, build and be inspired.

7

Python is vs ==

617 views

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

Comments

  • Blank-mugshot
    brakhane

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

Add a comment