Why does this list swap fail?

Alain Ketterlin alain at universite-de-strasbourg.fr.invalid
Mon Nov 14 14:07:53 EST 2016


380162267qq at gmail.com writes:

> L=[2,1]
> L[0],L[L[0]-1]=L[L[0]-1],L[0]
>
> The L doesn't change. Can someone provide me the detail procedure of
> this expression?

From:

https://docs.python.org/3/reference/simple_stmts.html#grammar-token-assignment_stmt

| Although the definition of assignment implies that overlaps between the
| left-hand side and the right-hand side are ‘simultaneous’ (for example
| a, b = b, a swaps two variables), overlaps within the collection of
| assigned-to variables occur left-to-right, sometimes resulting in
| confusion. 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)

In your case:

- L[0] get 1 (from L[L[0]-1])
- L[L[0]-1] (from lhs) is now L[0], which gets 2 (from L[0] in rhs)

Since both operations happen in sequence (not simultaneously), you just
overwrite the first element twice.

Congratulations, a very good corner case (you can't call it a bug, since
it conforms to the definition of the language).

-- Alain.



More information about the Python-list mailing list