>>> a=1
>>> b=1
>>> id(a)
140472563599848
>>> id(b)
140472563599848
>>> x=()
>>> y=()
>>> id(x)
4298207312
>>> id(y)
4298207312
>>> x1=(1)
>>> x2=(1)
>>> id(x1)
140472563599848
>>> id(x2)
140472563599848
until this point I was thinking there will be only one copy of immutable object and that will be shared(pointed) by all the variables.
But when I tried, the below steps I understood that I was wrong.
>>> x1=(1,5)
>>> y1=(1,5)
>>> id(x1)
4299267248
>>> id(y1)
4299267320
can anyone please explain me the internals?
is actually the same as
In Python, smaller numbers are internally cached. So they will not be created in the memory multiple times. That is why
id
s ofx1
andx2
are the same till this point.An one element tuple should have a comma at the end, like this
When you do this, there are two new tuples to be constructed with only one element in it. Even though the elements inside the tuples are the same, they both are different tuples. That is why they both have different
id
s.Lets take your last example and disassemble the code.
Now,
would produce something like this
It loads a constant value, referred by the index
3
, which is(1, 5)
and then stores it inx1
. The same way, it loads another constant value, at index4
and stores it iny1
. If we look at the list of constants in the code object,will give
The elements at positions
3
and4
are the tuples which we created in the actual code. So, Python doesn't create only one instance for every immutable object, always. Its an implementation detail which we don't have to worry much about anyway.Note: If you want to have only one instance of an immutable object, you can manually do it like this
Now, both
x2
andx1
will refer the same tuple object.