[Tutor] is v == for small ints

Alan Gauld alan.gauld at btinternet.com
Mon Dec 14 20:54:30 EST 2015


Somebody posted a question about this today and I approved
it but it hasn't shown up. We have had about 6 or 7 such
problems in the last month. Mainly they have been thank-you
messages so I didn't make an issue of it but a couple
have been genuine questions, like this was.

So if you have posted recently and it hasn't got through,
my apologies, but I have no idea what is going wrong.

As to the content of this message, the gist was that he had
tried 'is' and == with both small and large ints. When using
small ints the results were the same for both operators but
for large ints they differed. He knew the conceptual difference
between 'is' and == but didn't understand why the results
were different for large/small ints.

The answer is of course that small ints are cached internally
as an optimisation so all references to 5, for example,
refer to the same object in memory and therefore both is
(object identity) and == (value equality) are true. Large
ints result in two separate objects each with the same
value so 'is' becomes False and == remains true.

This behaviour should never be relied on since the definition
of a "small int" is potentially implementation dependant and
could even change with Python version or platform. Always
use == to test integers.

Apologies again about the missing messages.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list