Why are some python objects necessarily unique?

58 Views Asked by At

This is not a question of when to use is and when to use ==. I know that is checks if id of objects match and == checks if the values match.

Please have a look at the following.

>>> x = 3
>>> y = 3
>>> x is y
True
>>> m = 3.0
>>> n = 3.0
>>> m is n
False
>>> x = "spam"
>>> y = "spam"
>>> x is y
True
>>> a = ("s","p","a","m")
>>> b = ("s","p","a","m")
>>> a is b
False

You will notice that for the str- and int-variables, they are always automatically referring to the same object. But that is not the case for the tuple or float.

I am looking for an explanation why that is the case. Of course, I can go through all the types in this way, and write down when this happens, and when it does not. That is not an explanation.

This also happens with bool and NoneType. But it does not happen with function. And so on. Its easy to check all of these, but that doesn't give any insight. I have searched google for 'unique objects in python', and not really getting anything there. I also looked on YouTube. I ruled out that this has anything to do with immutability because both integers and floats are immutable.

The behavior changes if I do something like this

>>> def same(x, y):
...     u = x
...     v = y
...     return u is v
...
>>> same(1.0, 1.0)
True
0

There are 0 best solutions below