Reuse of primitive objects
suggest changeAn interesting thing to note which may help optimize your applications is that primitives are actually also refcounted under the hood. Let’s take a look at numbers; for all integers between -5 and 256, Python always reuses the same object:
>>> import sys
>>> sys.getrefcount(1)
3221225472
>>> a = 1
>>> b = 1
>>> sys.getrefcount(1)
3221225472
a is b is still true, so a and b reference the same 1. Since Python 3.12 those interned ints are immortal, and this count does not rise when another name is bound. The older transcript that went from 797 to 799 was the pre-immortal refcount. However, for larger numbers, Python actually doesn’t reuse the underlying object:
>>> a = 999999999
>>> sys.getrefcount(999999999)
2
>>> b = 999999999
>>> sys.getrefcount(999999999)
2
Because the refcount for 999999999 does not change when assigning it to a and b, and a is b is false when the statements are typed separately, they refer to two different underlying objects, even though they both are assigned the same primitive. The count includes getrefcount’s temporary and was 2 here; the old transcript showed 3.