4

Please clarify my doubt about python identity operators is and is not.

a,b = 10.0, 10.0
print (a is b)

will result in True

where as

a = 10.0
b = 10.0
print (a is b)

will result in False

Why in the first case the id() function results is same value and different in the second case

Isma
  • 14,604
  • 5
  • 37
  • 51
  • 2
    In both cases it prints true – Mufeed Jul 10 '18 at 07:05
  • 3
    Because unimportant implementation details. It doesn't matter. Python doesn't promise what either of these comparisons will return. – user2357112 Jul 10 '18 at 07:06
  • I can reproduce OPs behaviour using python 3.6. Using python 2.7 both are `False`. – Zinki Jul 10 '18 at 07:06
  • I got both True using Python 3.6 – Mufeed Jul 10 '18 at 07:07
  • 2
    @Mufeed: You probably ran the snippets as scripts instead of interactively. The behavior is different because more unimportant implementation details. – user2357112 Jul 10 '18 at 07:07
  • Yes. I ran as script. – Mufeed Jul 10 '18 at 07:08
  • 1
    Can you explain in detail why it happens? @user2357112 – Mufeed Jul 10 '18 at 07:10
  • 2
    That's a little dismissive, @user2357112 – the OP is obviously interested in why this happens and if you find it too unimportant to bother with, you can just move on. – xnx Jul 10 '18 at 07:12
  • 2
    @xnx But the Python language basically explicitly defines that both `True` and `False` are possible here, so any code that relies n either is incorrect. There are interesting questions here, but they're (a) specific to a particular implementation, and (b) lower level than this. For example, in this case, the reason the first one is true is an artifact of CPython's compiler constant folding (which isn't true for, say, Jython), and the reason the second is false is that each statement is a separate compilation unit (which isn't true if you put the exact same code in a module or script). – abarnert Jul 10 '18 at 07:33
  • @abarnert That's pretty much the basis of a decent answer to the question, which I think is a reasonable one for anyone curious about better understanding the language to ask. In any case the duplicate assigned to it provides plenty to go on. – xnx Jul 10 '18 at 07:44
  • @abarnert thanks for the clarifications. – Ashok Sengupta Jul 10 '18 at 09:14

0 Answers0