Skip to content Skip to sidebar Skip to footer

Why Does Looking Up An Index *before* A Swap Rather Than Inline Change The Result?

Consider the following code: data1 = [1.48, -4.96] data2 = [1.48, -4.96] # i is index we want to swap; mn is the data we want to swap the content of index-i with i = 0; mn = dat

Solution 1:

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.

Post a Comment for "Why Does Looking Up An Index *before* A Swap Rather Than Inline Change The Result?"