Why do these statements evaluate the way they do?

Chris Angelico rosuav at gmail.com
Sat May 7 02:48:22 EDT 2016


On Sat, May 7, 2016 at 4:36 PM, Anthony Papillion
<anthony at cajuntechie.org> 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.

Frankly, you shouldn't care. Integers and strings should always be
compared for equality ("=="), not identity ("is"). Everything else is
an interpreter optimization; what you'll find is that some small
integers are cached deep within CPython, so the integer 7 is always
the same object. The exact set that's cached varies from version to
version of CPython, and other interpreters mightn't do that at all -
or might not even have actual in-memory objects for *any* integers in
the machine word range, using their values directly. Or anything at
all.

ChrisA



More information about the Python-list mailing list