Swapping items in container - evaluation order

67 Views Asked by At

Edited for clarity:

Why do the list items not swap?

# python 3.5
lst = [0, 1]
lookup = {0: 1, 1: 0}

lst[0], lst[lookup[lst[0]]] = lst[lookup[lst[0]]], lst[0]
# lst is still unchanged; why aren't items 0 and 1 not swapped
2

There are 2 best solutions below

0
On BEST ANSWER

The rhs is evaluated before the lhs. That's not the problem.

The problem is how the lhs is evaluated. You can prove this to yourself by running this statement:

lst[0], lst[lookup[lst[0]]] = 1, 0

Note that the assigning to lst[0] occurs before the evaluation of lst[lookup[lst[0]]]. So the lst[0] in that complex expression is the new value, not the old value.

Breaking it down:

lst[0], lst[lookup[lst[0]]] = 1, 0
=> lst[0] = 1; lst[lookup[lst[0]]] = 0
=> lst[0] = 1; lst[lookup[1]] = 0
=> lst[0] = 1; lst[0] = 0

So the final result appears unchanged.

0
On

Because:

lst[0], lst[lookup[lst[0]]] = lst[lookup[lst[0]]], lst[0]

is equivalent to:

lst[0]= lst[lookup[lst[0]]]
lst[lookup[lst[0]]] = lst[0]