Clarification on Immutability please

Random832 random832 at fastmail.com
Tue Jan 28 09:47:40 EST 2020


On Wed, Jan 22, 2020, at 02:34, Stephen Tucker wrote:
> Oh dear, I am sorry. I have created quite a storm.
> 
> Moreover, I am sorry because I misremembered what I had typed into Idle. My
> original tuple only had two elements, not three, so the slicing [:2] didn't
> affect the tuple at all - and so the second id() gave the same address as
> the first one.
> 
> So, yes, I am stupid - or just having senior moments (I am 65, after all).
> 
> Stephen.

Regardless, this is interesting because, even though it is not in fact the case, this would be a valid optimization for an interpreter to perform, and while it's not done, something similar is done when concatenating strings.

>>> s = 'asdfghjklmnop'
>>> id(s); s += 'x'; id(s)
20405128
27766160
>>> id(s); s += 'x'; id(s)
27766160
27766160
# if this is done repeatedly, the two ids will not always be the same, but they will be quite a bit more often than not.

The two tuples, if there are  do not exist at the same time, therefore it does not violate any constraint if their ids are the same - ids are only required to be unique for simultaneously existing objects, not across the lifetime of the program.


More information about the Python-list mailing list