packing unpacking depends on order.

Terry Reedy tjreedy at udel.edu
Wed Sep 2 13:26:43 EDT 2015


On 9/2/2015 8:26 AM, Steven D'Aprano wrote:
> On Wed, 2 Sep 2015 08:01 pm, Antoon Pardon wrote:
>
>>
>>>>> a = [1, 2, 3, 4, 5]
>>>>> b = 1
>>>>> b, a[b] = a[b], b
>>>>> a
>> [1, 2, 1, 4, 5]
>
> Equivalent to:
>
> temp1 = a[b]  # a[1] == 2
> temp2 = b  # 1
> b = temp1  # b = 2
> a[b] = temp2  # a[2] = 1
>
>
> Or using a queue (FIFO) rather than temp variables:
>
> push a[b]
> push b
> b = pop
> a[b] = pop
>
>
> which seems sensible to me. The right hand side of the assignment is
> evaluated left-to-right, and then the assignments are made, from
> left-to-right. Which I believe matches the documented order.

It does, and '7.2 Assignment statements' ends with this example:
"""
For instance, the following program prints [0, 2]:
x = [0, 1]
i = 0
i, x[i] = 1, 2         # i is updated, then x[i] is updated
print(x)
"""

-- 
Terry Jan Reedy




More information about the Python-list mailing list