-1

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
max
  • 49,282
  • 56
  • 208
  • 355

2 Answers2

1

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.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

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]
bits
  • 1,595
  • 1
  • 17
  • 17