2

In python,

>>>a=5
>>>b=5
>>>a is b
True

But,

>>>a=300
>>>b=300
a is b
False

I understand the code above, but...

a=[300,300]
a[0] is a[1]
True

Why is the result of this code 'True'?

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
minsoo
  • 39
  • 3

1 Answers1

2

In the standard case of object programming: when you create a new object, the language/computer will reserve a new memory space and adress for it.

There is a special case in Python as numbers are immutable and will never change, so Python may optimizes this by pointing to the same memory address when the same number is reused, this applies for numbers between -5 and 256. (it is a kind of Singleton pattern)

Warning This may be a specific implementation detail and a undefined behavior, so you should not rely on it.

This optimization choice was made because creating a new number object each time would have been too much time and memory consuming. And also the number of memory allocation/deallocation would have been too much also.

So working with "is" operator may return true is the two numbers are the same and between -5 and 256.

Best Practice Do not rely on this implementation which may change And there is no point using the "is" operator here, working with "==" to compare content and not adresses is the way to go.

Malo
  • 1,233
  • 1
  • 8
  • 25
  • 2
    "So working with "is" operator will always return true is the two numbers are the same." no, that's false – juanpa.arrivillaga Jun 09 '21 at 08:28
  • @juanpa.arrivillaga Yup you are correct. For instance "x = 1000 y = 500+500 x is y" will return False, however "1000 is 500+500" will return True – Tom McLean Jun 09 '21 at 09:16
  • 1
    However "x = 1 y = 1 x is y" will return True because the values are between -5 and 256, so are always stored in the same id – Tom McLean Jun 09 '21 at 09:19
  • @TomMcLean thanks for the precise range of number where it applies – Malo Jun 09 '21 at 10:22
  • This is also only for Cython – Tom McLean Jun 09 '21 at 10:31
  • have you an explanation why it is not consistent depending of where number is stored in list or variable ? ll[0] is ll[1] Out[72]: True ; 300 is 300 Out[73]: True ; a = 300 ; b = 300 ; a is b Out[76]: False – Malo Jun 09 '21 at 11:25
  • moreover how do I know if I use Cython ? I did the checks in my Python 3.7 and with Spyder 5 IDE .... – Malo Jun 09 '21 at 11:27
  • @Malo This answer will explain why 300 is 300 returns True: https://stackoverflow.com/questions/34147515/the-is-operator-behaves-unexpectedly-with-non-cached-integers – Tom McLean Jun 09 '21 at 16:25
  • 1
    @TomMcLean *CPython – juanpa.arrivillaga Jun 09 '21 at 16:57