Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #108257
| From | Kev Dwyer <kevin.p.dwyer@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Why do these statements evaluate the way they do? |
| Date | 2016-05-07 08:04 +0100 |
| Message-ID | <mailman.448.1462604660.32212.python-list@python.org> (permalink) |
| References | <9D4F2568-405C-419B-9B18-7376B34143CD@cajuntechie.org> <ngk416$uol$1@ger.gmane.org> |
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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Why do these statements evaluate the way they do? Kev Dwyer <kevin.p.dwyer@gmail.com> - 2016-05-07 08:04 +0100
csiph-web