0

In Python if

a = 1
b = 1
print(a is b) 

returns True.

However, if

c = 1.23
d = 1.23

print(c is d) 

returns False.

It appears for the float data type the output is False. Can someone explain to me why does python behave this way?

a = 1
b = 1

print(a is b)
#Output: True

c = 1.23
d = 1.23
print(c is d)
#Output: False
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Mohammed Ansari
  • 31
  • 1
  • 1
  • 2

2 Answers2

2

Take a look at this:

>>> a = 1
>>> b = 1
>>> print(a is b)
True
>>> c = 1.2
>>> d = 1.2
>>> print(c is d)
False
>>> hex(id(a))
'0x77fb6c20'
>>> hex(id(b))
'0x77fb6c20'
>>> hex(id(c))
'0x2185c8e1990'
>>> hex(id(d))
'0x2185c8e1a38'
>>> a = 900
>>> b = 900
>>> print(a is b)
False
>>> hex(id(a))
'0x2185d434e10'
>>> hex(id(b))
'0x2185d434eb0'
>>> 

As you can see here when a and b are 1, the memory location of the variables is same as they are cached by the python runtime. c and d are referred at different memory locations due to their data type being float. When we take a large value for a and b, their memory location is different. is statement in python isn't a comparison operator but tells if the variables referred are bound to the same objects.

As per here:

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)

0

Because the Python runtime caches some small integers so that they can be reused. Other numbers aren't cached, and require object allocation each time one is created. is tests if two objects are the same object, not just two objects with the same numerical value.

You should not rely on this optimisation. Always test numerical equality with ==.

rici
  • 234,347
  • 28
  • 237
  • 341