# Tuples and immutability

Oscar Benjamin oscar.j.benjamin at gmail.com
Wed Mar 12 11:20:25 CET 2014

```On 12 March 2014 03:25, Terry Reedy <tjreedy at udel.edu> wrote:
> On 3/11/2014 10:01 PM, Rick Johnson wrote:
>>
>>
>> On Thursday, February 27, 2014 4:18:01 PM UTC-6, Ian wrote:
>>>
>>> x += y is meant to be equivalent, except possibly in-place and
>>> more efficient, than x = x + y.
>
>
> The manual actually says "An augmented assignment expression like x += 1 can
> be rewritten as x = x + 1 to achieve a similar, but not exactly equal
> effect. In the augmented version, x is only evaluated once. Also, 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
>
>
>
>> In an ideal world, the speed of these two codes should be the same,
>
>
> Nope, 'similar' is not 'equivalent'. Evaluating x twice instead of once and
> possibly allocating a new object versus not take extra time. In a statement
> like "x.y.z[3*n+m] += 1", calculating the target dominates the time to
> increment, so this form should be nearly twice as fast.

An example where the result is semantically different:

>>> from numpy import array
>>> a = array([1, 2, 3], dtype=int)
>>> a
array([1, 2, 3])
>>> a + 1.1
array([ 2.1,  3.1,  4.1])
>>> a += 1.1
>>> a
array([2, 3, 4])

The reason is that numpy arrays are both mutable and have statically
determined elementary data type:

>>> (a + 1.1).dtype
dtype('float64')
>>> a.dtype
dtype('int64')

Oscar

```