Clarification on Immutability please

Chris Angelico rosuav at gmail.com
Tue Jan 21 13:38:12 EST 2020


On Wed, Jan 22, 2020 at 4:42 AM Stephen Tucker <stephen_tucker at sil.org> wrote:
>
> Hi Python-list folk,
>
> I am sure this has been answered many times before, but I need to ask it
> again.
>
> Given that the following is valid Python 2.7.10 (when keyboarded into Idle):
>
> mytup = ("q", "w", "e")
> id(mytup)
> mytup = mytup [:2]
> id(mytup)
>
> and even that the first id(mytup) returns the same address as the second
> one, I am left wondering exactly what immutability is.

Are you sure that it does? I can't reproduce this. When you slice the
first two from a tuple, you create a new tuple, and until the
assignment happens, both the new one and the original coexist, which
means they MUST have unique IDs. Can you post an exact copy and paste
from Idle, including the version string that gets posted on startup?
Also, since it's 2020 and Python 2 is basically defunct, can you
reproduce this in Python 3?

> I am left concluding that mytup is not actually a tuple (even though type
> (mytup) tells me that it is).

If type(mytup) is tuple, then mytup really truly is a tuple. There is
no other conclusion.

> My only explanation is that mytup is, actually, a pointer to a tuple; the
> pointer can't change, but the contents of that pointer (or the data to
> which the pointer points) can change.

Incorrect. Python simply doesn't have that concept.

> That said, if I then type
>
> mytup = mytup + ("r", "t")
> id(mytup)
>
> I find that this third id call returns a different address from the one
> returned by the first two.
>
> Somehow, it seems, tuples can be reduced in length (from the far end)
> (which is not what I was expecting), but they cannot be extended (which I
> can understand).
>
> I am probably confused, ignorant, stupid, or any combination of the above.

Or misreading the ID numbers, which can get very very large :)

> Can you please help me become less so?

Happily! :)

ChrisA


More information about the Python-list mailing list