Tuples and immutability
Gregory Ewing
greg.ewing at canterbury.ac.nz
Sun Mar 9 18:03:59 EDT 2014
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 to
the target, the old object is modified instead."
Note that it says "when possible", not "if the implementation
feels like it".
> In fact, if you read the documentation for lists, you may notice that
> while they clearly cover the + operator and the extend method, they do
> not explicitly document the list class's += operator.
The "when possible" clause, together with the fact that lists
are mutable, implies that it *will* be done in-place. There
is no need to document all the in-place operators explicitly
for every type.
--
Greg
More information about the Python-list
mailing list