Links and copies in python
So, I tried something from python and stumbled upon this by accident:
>>> a = 10
>>> b = 10
>>> a is b
True
Apparently, when creating a variable, b
Python notes that there is already another (different) variable with a value of 10 and just creates a reference to it (just to save memory, maybe?). Since integers are immutable (at least I think they are), this makes some sense. But then I tried the same with a large number and got this:
>>> a = 100200103847239642631982367
>>> b = 100200103847239642631982367
>>> a is b
False
Here for some reason Python creates another object int
instead of making the variable a variable b
reference a
, which doesn't make sense to me. Assuming the links created in the first example are memory saves, wouldn't it be even more efficient to create the link in the latter case as well, since the numbers are larger?
source to share
Python usually caches integers between -5 and 256 (although this may differ between implementations); when two names point to the same cached integer, they have the same ID and therefore point to the same object:
>>> c = 10
>>> d = 10
>>> id(c) == id(d)
True
>>> c is d
True
However, if you violate this cache threshold, the identifiers change:
>>> e = 256
>>> d = 256
>>> id(e) == id(d)
True
>>> d = 257
>>> e = 257
>>> id(d) == id(e)
False
>>> d is e
False
>>> f = -5
>>> g = -5
>>> id(f) == id(g)
True
>>> f = -6
>>> g = -6
>>> id(f) == id(g)
False
You see the same effect.
Keep in mind that is
doesn't compare values, don't use is
when you really mean "equal":
>>> 10 * 1000 is 10000
False
>>> 10 * 1000 == 10000
True
source to share