[Solved] Why does looking up an index *before* a swap rather than inline change the result?


Let’s add some tracing so we can see order-of-operations:

import sys

def findIdx(ary, tgt):
    retval = ary.index(tgt)
    print('First instance of %r in %r is at position %r' % (tgt, ary, retval), file=sys.stderr)
    return retval

data1 = [1.48,  -4.96]
i = 0
mn = data1[1]

k = findIdx(data1, mn)
data1[i], data1[k] = data1[k], data1[i]
print("Prior lookup:  %r" % data1)

data2 = [1.48,  -4.96]
data2[i], data2[findIdx(data2, mn)] = data2[findIdx(data2, mn)], data2[i]
print("Inline lookup: %r" % data2)

The logs are then elucidating:

First instance of -4.96 in [1.48, -4.96] is at position 1
Prior lookup:  [-4.96, 1.48]
First instance of -4.96 in [1.48, -4.96] is at position 1
First instance of -4.96 in [-4.96, -4.96] is at position 0
Inline lookup: [1.48, -4.96]

As you can see, the last call to lookup the index is doing so against an array that has already had one of its two elements replaced.

1

solved Why does looking up an index *before* a swap rather than inline change the result?