Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncommon behaviour of IS operator in python

Tags:

python

From some of the answers on Stackoverflow, I came to know that from -5 to 256 same memory location is referenced thus we get true for:

>>> a = 256
>>> a is 256
True

Now comes the twist (see this line before marking duplicate):

>>> a = 257
>>> a is 257 
False 

This is completely understood, but now if I do:

>>> a = 257; a is 257
True
>>> a = 12345; a is 12345
True

Why?

like image 759
Ritesh Avatar asked Jun 15 '18 19:06

Ritesh


1 Answers

Generally speaking, numbers outside the range -5 to 256 will not necessarily have the optimization applied to numbers within that range. However, Python is free to apply other optimizations as appropriate. In your cause, you're seeing that the same literal value used multiple times on one line is stored in a single memory location no matter how many times it's used on that line. Here are some other examples of this behavior:

>>> s = 'a'; s is 'a'
True
>>> s = 'asdfghjklzxcvbnmsdhasjkdhskdja'; s is 'asdfghjklzxcvbnmsdhasjkdhskdja'
True
>>> x = 3.14159; x is 3.14159
True
>>> t = 'a' + 'b'; t is 'a' + 'b'
True
>>> 
like image 72
BallpointBen Avatar answered Oct 19 '22 02:10

BallpointBen