How to extend a tuple of tuples?

Chris Angelico rosuav at gmail.com
Mon Sep 12 17:29:36 EDT 2016


On Tue, Sep 13, 2016 at 7:19 AM, BartC <bc at freeuk.com> wrote:
> By the same argument, then strings and ints are also mutable.
>
> Here, the original tuple that a refers to has been /replaced/ by a new one.
> The original is unchanged. (Unless, by some optimisation that recognises
> that there are no other references to it, the original is actually appended
> to. But in general, new objects are constructed when implementing +=.)

And by definition, that optimization cannot be detected. At best, all
you could do is something like:

old_id = id(a)
a += something
if id(a) == old_id:
    print("We may have an optimization, folks!")

But that can have false positives. If two objects do not concurrently
exist, they're allowed to have the same ID number.

ChrisA



More information about the Python-list mailing list