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?

2

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

I just did a = 0.0; b = 0.0 and then b is a said True.
Well you're not doing what I said. I didn't say I did a = 0.0 and then did b = 0.0. I said I did a = 0.0; b = 0.0. Try that.
@StefanPochmann did you mean this imgur.com/a/rYKCL? If not, can you provide a sample?
Yes, that's what I mean. I guess you're using IPython and it does things differently. Try it in a Python shell, like the OP apparently did (as indicated by the >>>). I do get True there.
@StefanPochmann Noted! and thanks. I am pretty used to IPython and do not tend to used python shell. Also, it does return True there. Something for me to ponder why :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.