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'?
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'?
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.