Python - Why is the 'is' operator returning true in this situation?

Viewed 303

I am new to Python so my question may seem obvious. But according to W3Schools two variables are only the same under an 'is' operator if they reference the same object. So my question is, why does following return True? I thought Python creates two separate memory locations for them?

a = 500
b = 500

print(a == b) # True
print(a is b) # True, why is this true?
3 Answers

Are you sure that works for the value 500?

Python 3.8.10 (default, Jun  2 2021, 10:49:15)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 500
>>> b = 500
>>> a is b
False
>>> b = 100
>>> a = 100
>>> a is b
True
>>>

Preallocation in Python

In Python, upon startup, Python3 keeps an array of integer objects, from -5 to 256. For example, for the int object, marcos called NSMALLPOSINTS and NSMALLNEGINTS are used:

#ifndef NSMALLPOSINTS
#define NSMALLPOSINTS           257
#endif
#ifndef NSMALLNEGINTS
#define NSMALLNEGINTS           5
#endif
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
/* References to small integers are saved in this array so that they
   can be shared.
   The integers that are saved are those in the range
   -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
*/
static PyIntObject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
#endif
#ifdef COUNT_ALLOCS
Py_ssize_t quick_int_allocs;
Py_ssize_t quick_neg_int_allocs;
#endif

What does this mean? This means that when you create an int from the range of -5 and 256, you are actually referencing to the existing object.

Reference: https://medium.com/@kjowong/everything-is-an-object-in-python-928f2a7d3e15

it's usually a matter of optimization. it will split when u change one of the values (and occupy 2 places in memory)

Related