Anthony Papillion wrote: > I'm trying to figure out why the following statements evaluate the way > they do and I'm not grasping it for some reason. I'm hoping someone can > help me. > > 40+2 is 42 #evaluates to True > But > 2**32 is 2**32 #evaluates to False > > This is an example taken from a Microsoft blog on the topic. They say the > reason is because the return is based on identity and not value but, to > me, these statements are fairly equal. > > Can someone clue me in? > > Anthony
The *is* operator tests for identity, that is whether the objects on either side of the operator are the same object. CPython caches ints in the range -5 to 256 as an optimisation, so ints in this range are always the same object, and so the is operator returns True. Outside this range, a new int is created as required, and comparisons using is return False. This can be seen by looking at the id of the ints: Python 3.5.1 (default, Dec 29 2015, 10:53:52) [GCC 4.8.3 20140627 [gcc-4_8-branch revision 212064]] on linux Type "help", "copyright", "credits" or "license" for more information. >>> a = 42 >>> b = 42 >>> a is b True >>> id(a) 9186720 >>> id(b) 9186720 >>> c = 2 ** 32 >>> d = 2 ** 32 >>> c is d False >>> id(c) 140483107705136 >>> id(d) 140483107705168 -- https://mail.python.org/mailman/listinfo/python-list