0

When string is typecasted to float, why does it get a different id, unlike when typecasted to int?

I thought it would be same for both.

Can anyone explain what is actually happening when string is converted to float?

It should get the same id when the same object is already available (as mentioned in Python Documentation)

a = 5
b = "5"

id(a) == id(int(b))
# which comes True
# But

x = 5.0
y = "5.0"

id(x) == id(float(y))
# comes False
# Why ?

I expected it to be True, but it's False.

Jon Jaussi
  • 1,298
  • 3
  • 18
  • 36
Omi
  • 111
  • 8
  • 1
    That's basic computer science problem - Floating point error - You can't compare two floats without tolerance read https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – SMA Dec 23 '18 at 14:26
  • 1
    That's not it, @SMA, as there are no inaccuracies involved here. This is about the difference between equality and identity of objects that have the same value. What this particular Python implementation does is called "interning" of values. – Ulrich Eckhardt Dec 23 '18 at 14:35

1 Answers1

0

What I think you're seeing is an effect of interning. For performance reasons, Python interns certain objects that are likely to be used frequently, such as short strings and small integers. This means there is only ever one instance of these objects, so equality testing (== operator) is the same as identity testing (is operator or comparing the id()s). 5 apparently is one of those integers, but I just tried your test with a=9999 and b="9999" and observed that the id comparison was False. (By the way, your id equality test could be written in terms of the is operator, as "a is int(b)".)

I think this sort of thing is usually considered an implementation detail; Python is able to get away with this because strings and ints are immutable, but using the equality (==) operator is generally a good idea when you're asking the question "does x equal y?". The result of == won't depend on whether the implementation decides to intern the objects in question.

Apparently the developers decided doing the same with floats isn't worth the trouble, though I suppose they could have, given that floats are immutable too.

CanterChin
  • 19
  • 2