Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #108257 > unrolled thread
| Started by | Kev Dwyer <kevin.p.dwyer@gmail.com> |
|---|---|
| First post | 2016-05-07 08:04 +0100 |
| Last post | 2016-05-07 08:04 +0100 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Why do these statements evaluate the way they do? Kev Dwyer <kevin.p.dwyer@gmail.com> - 2016-05-07 08:04 +0100
| From | Kev Dwyer <kevin.p.dwyer@gmail.com> |
|---|---|
| Date | 2016-05-07 08:04 +0100 |
| Subject | Re: Why do these statements evaluate the way they do? |
| Message-ID | <mailman.448.1462604660.32212.python-list@python.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 top | Article view | comp.lang.python
csiph-web