0

I am noticing something peculiar about identity comparison for integers, below and above 256, in python. Take a look at below code.

a = 256 # or any number below
b = 256
print(a is b) # True
a = 257 # or any number above
b = 257
print(a is b) # False

This my guess is that since a number > 256 doesn't fit in an 8 bit memory location, python moves it else where and stores a pointer instead. (I'm not a CS graduate, probably my understanding is completely wrong).

However, if I use multiple assignment. Things are different.

a, b = 257, 257 # or any number above
print(a is b) # True

Is this by design? May be for optimizing memory? Why does python behave like this?

ps: I am using Python 3.6.1

najeem
  • 1,841
  • 13
  • 29
  • 3
    Hi, I couldn't understand why this was marked duplicate of question about 'is' operator. My question was more about multiple assignment! – najeem Jan 28 '19 at 03:44
  • 1
    The duplicate is wrong, but https://stackoverflow.com/q/34147515/ is related. – iz_ Jan 28 '19 at 03:49
  • This is not related to duplicate assignment at all. The issue is this design choice "*The current implementation keeps an array of integer objects for all integers between -5 and 256*" (https://docs.python.org/3/c-api/long.html). In the last example in your code (with the tuple assignment), you're getting two different copies of 257, while the implementation assures that this cannot happen with smaller integers. – yoniLavi Jan 28 '19 at 03:54
  • @Tomothy32, Thanks for the link. That answers my question! – najeem Jan 28 '19 at 04:04

0 Answers0