Python - is vs ==

Today I am going to explain a scenario to differentiate is and == operators.

I've got a python program as follows,


           >>> a=255
           >>> b=255
           >>> a is b
           True
           >>> a=257
           >>> b=257
           >>> a is b
           False
           
This is because, is is identity testing, == is equality testing. what happens in your code would be emulated in the interpreter like this:

           
           >>> a = 'pub'
           >>> b = ''.join(['p', 'u', 'b'])
           >>> a == b
           True
           >>> a is b
           False
           
so, no wonder they're not the same, right? In other words: is is the id(a) == id(b)

           
           >>> a=255
           >>> b=255
           >>> id(a)
           144784368
           >>> id(b)
           144784368
           >>> a=255
           >>> a=257
           >>> b=257
           >>> id(a)
           145365120
           >>> id(b)
           145365108
           

So, when the char set exceeds 256, a new id is assigned and that's why identity check fails for the above case.

Leave a comment