0

My understanding is that all primitive types are referentially equal if they are equal in value.

With integers, this seems to be the case shown from the following example:

v1 = 2
v2 = 2
v1 is v2 # prints True

With booleans, this also seems to be the case shown from the following example:

v1 = False
v2 = False
v1 is v2 # prints True

With strings, it starts to get a little confusing. The following example follows the procedure:

v1 = 'testtest'
v2 = 'testtest'
v1 is v2 # prints True

However, as soon as I add a space to the string, it fails:

v1 = 'test test'
v2 = 'test test'
v1 is v2 # prints False

With floats, the pattern just doesn't exist:

v1 = 2.0
v2 = 2.0
v1 is v2 # prints False

Why do strings follow the rule except when spaces are added? Why do floats not follow the rule at all? Any help is appreciated.

  • 1
    "My understanding is that all primitive types are referentially equal if they are equal in value." - not sure where you got that idea, but your tests clearly show it's false. – user2357112 Jul 08 '21 at 09:04
  • Does this answer your question? [Is there a difference between "==" and "is"?](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is) – Alex Waygood Jul 08 '21 at 09:04
  • 1
    Python doesn't even have a concept of "primitive" types, anyway. This isn't Java. – user2357112 Jul 08 '21 at 09:04
  • 2
    TL;DR: certain small values are internally cached, *interned*. That's an optimisation detail you shouldn't worry about much. Simply never use `is` in this way, it's not supposed to be used for these operations. – deceze Jul 08 '21 at 09:22

1 Answers1

0

With integers, this seems to be the case shown from the following example:

v1 = 2
v2 = 2
v1 is v2 # prints True

You are spoiled by implementation detail which made certain integers to behave that way, consider counter-example:

t1 = 1000000
t2 = 1000000
print(t1 is t2)  # False
Daweo
  • 31,313
  • 3
  • 12
  • 25