0

Could someone answer below (Output is from IDLE or check on python shell - python 2.7). For 1),2) and 3),4) I am doing exactly same operation but getting different results.

1) >>> a=0

2) >>> a is 0

True

3) >>> a=0.0

4) >>> a is 0.0

False

5) >>> 0.0 is 0.0

True

why 4) is False?

vsk
  • 23
  • 4
  • Possible duplicate of [Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?](http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce) – Nickil Maveli Feb 11 '17 at 10:09
  • 1
    Since the answers don't properly account for it, let me note that (IIRC), you should expect 5) to be false too -- it only turns out to be true because of an optimization in the parser. I don't have a reference, though. –  Feb 11 '17 at 10:18

2 Answers2

1

The python is operator is used to test if two variables point to same object.

From the documentation:

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object.

For eg.

a = 0.0

if you do b = a and then follow it up with b is a. It will return True.

Now if you do a = 0.0 and b = 0.0 and then try b is a it will return False, because now a and b are two variables pointing to two different objects.

Rajesh Yogeshwar
  • 2,111
  • 2
  • 18
  • 37
1

This is because an optimization in CPython that for any integer between -5 and 256 returns a reference to an already existing object, meaning a is a reference to 0, so they have the same id(). There is no such optimization for floating point numbers like 0.0, so a new object is created on assignment (meaning that id(a) != id(0.0)).

Reference: https://docs.python.org/2/c-api/int.html

Dean Fenster
  • 2,345
  • 1
  • 18
  • 27