Tuples and immutability
ian.g.kelly at gmail.com
Mon Mar 10 00:42:42 CET 2014
On Sun, Mar 9, 2014 at 4:03 PM, Gregory Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> Ian Kelly wrote:
>> In my view the second one is wrong. a += b should be understood as
>> being equivalent to a = a + b, but with the *possible* and by no means
>> guaranteed optimization that the operation may be performed in-place.
> This interpretation is at odds with the Language Reference,
> section 6.2.1, Augmented Assignment Statements:
> "An augmented assignment expression like x += 1 can be rewritten as x = x +
> 1 to
> achieve a similar, but not exactly equal effect... when possible, the actual
> operation is performed
> in-place, meaning that rather than creating a new object and assigning that
> the target, the old object is modified instead."
> Note that it says "when possible", not "if the implementation
> feels like it".
That's quite vague, and not much stronger a guarantee than "maybe".
It's technically "possible" for this augmented assignment to be
performed in place:
x = 12
x += 4
But it's not done in-place, because ints are meant to be immutable.
In any case, this means that whether the operation is actually
performed in-place is an implementation detail -- if not of the Python
implementation then at least of the class -- and not something the
user should take for granted.
More information about the Python-list