The Python Oracle

Different results in IDLE and python shell using 'is'

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 Question
00:42 Accepted answer (Score 5)
01:55 Answer 2 (Score 0)
02:55 Thank you

--

Full question
https://stackoverflow.com/questions/6845...

Accepted answer links:
[should not rely on is]: https://stackoverflow.com/questions/1329...
[What's with the integer cache maintained by the interpreter?]: https://stackoverflow.com/a/15172182/576...
[Different behavior in python script and python idle?]: https://stackoverflow.com/q/31260988/576...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #pythonidle

#avk47



ACCEPTED ANSWER

Score 5


You should not rely on is for comparison of values when you want to test equality.

The is keyword compares id's of the variables, and checks if they are the same object. This will only work for the range of integers [-5,256] in Python, as these are singletons (these values are cached and referred to, instead of having a value stored in memory). See What's with the integer cache maintained by the interpreter? This is not the same as checking if they are the same value.

As for why it behaves differently in a REPL environment versus a passed script, see Different behavior in python script and python idle?. The jist of it is that a passed script parses the entire file first, while a REPL environment like ipython or an IDLE shell reads lines one at a time. a=10.24 and b=10.24 are executed in different contexts, so the shell doesn't know that they should be the same value.




ANSWER 2

Score 0


In python editor

a = 10.24
b = 10.24
print(id(a),id(b))

output -

2079062604112 2079062604112

If we relate this to C, then 2079062604112, 2079062604112 are actually the memory address, here in Python it is the unique id,which are same in python editor.

In shell-

>>> a = 10.24
>>> b = 10.24
>>> id(a)
2254043146288 # output
>>> id(b)
2254043400016 # output

Giving different unique id.
So when is used for comparison it compares the unique id's that's why u are getting different answers.
Hope you finds this helpful.