packing unpacking depends on order.

Steven D'Aprano steve at pearwood.info
Wed Sep 2 14:26:08 CEST 2015


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.


>>>> a = [1, 2, 3, 4, 5]
>>>> b = 1
>>>> a[b], b = b, a[b]
>>>> a
> [1, 1, 3, 4, 5]

Likewise:

temp1 = b  # 1
temp2 = a[b]  # a[1] == 2
a[b] = temp1  # a[1] = 1
b = temp2  # b = 2



> I think I understand how it gets these results
> but I'm not really happy with them. I think python
> should give the second result in both cases.

Apart from breaking backwards compatibility, how would you implement such a
thing? A simple left-to-right assignment rule is easy to implement and easy
to understand even when the targets depend on each other.



-- 
Steven



More information about the Python-list mailing list