Swaping two elements in a list shows unexpected behaviour

In short, lis.index(max1) in left/right sides are evaluated at different times; then evaluated to different values (0 for the left side, 4 for the right side).


a, b = b, a

Above statement:

  • creates (b, a) tuple
  • unpacks the above tuple to a and b
    • a = old-value-of-b
    • b = old-value-of-a

lis[0], lis[lis.index(89)] = lis[lis.index(89)], lis[0]

becomes

lis[0], lis[lis.index(89)] = lis[4], lis[0]

=>

lis[0], lis[lis.index(89)] = 89, 0

=>

lis[0] = 89
lis[lis.index(89)] = 0

=>

lis[0] = 89
lis[0] = 0    # NOTE lis.index(89) == 0  at this point

So lis[0] assigned 89, then assigned original value 0 back. => (only the first element changed, and re-assigned original value)


To avoid this problem, assign the index before the swap statement:

idx = lis.index(89)
lis[0], lis[idx] = lis[idx], lis[0]