python - "is" operator behaves unexpectedly with integers -


why following behave unexpectedly in python?

>>> = 256 >>> b = 256 >>> b true           # expected result >>> = 257 >>> b = 257 >>> b false          # happened here? why false? >>> 257 257 true           # yet literal numbers compare 

i using python 2.5.2. trying different versions of python, appears python 2.3.3 shows above behaviour between 99 , 100.

based on above, can hypothesize python internally implemented such "small" integers stored in different way larger integers , is operator can tell difference. why leaky abstraction? better way of comparing 2 arbitrary objects see whether same when don't know in advance whether numbers or not?

take @ this:

>>> = 256 >>> b = 256 >>> id(a) 9987148 >>> id(b) 9987148 >>> = 257 >>> b = 257 >>> id(a) 11662816 >>> id(b) 11662828 

edit: here's found in python 2 documentation, "plain integer objects" (it's same python 3):

the current implementation keeps array of integer objects integers between -5 , 256, when create int in range reference existing object. should possible change value of 1. suspect behaviour of python in case undefined. :-)


Comments

Popular posts from this blog

Retrieving ETA (estimated time of arrival) with Google Distance Matrix API and public transit as transport mode -

javascript - Confirm a form & display message if form is valid with JQuery -

ionic framework - Meteor - Error: Failed to execute 'insertBefore' on 'Node' -