0

The following function replaces an integer from one list with the integer in the next list of the same position IF the second integer is larger... What im having trouble understanding is what the tmp variable does and how the actual swapping takes place inside the for loop...

def swapLowHigh(list1, list2):
    for i in range(0, len(list2)):
        if i < len(list1) and list1[i] < list2[i]:
            tmp = list2[i]
            list2[i] = list1[i]
            list1[i] = tmp

l1 = [1,9,5,4]
l2 = [2,8,7,3,8,1]

swapLowHigh(l1, l2)

print(l1)
print(l2)

#output
[2, 9, 7, 4]
[1, 8, 5, 3, 8, 1]
CosmicCat
  • 612
  • 9
  • 19
  • 1
    Try swapping two balls in two cups without a third place to put one of the balls (only one ball fits in a cup at a time). That third place (cup) is tmp. – JCampy Oct 25 '18 at 22:00
  • 1
    Imagine you have two boxes with one item in it each, and you wanted to put the item from each box into the other box. First you must move one item out of its box and put it somewhere, until you have made room for it by moving the other item. That place where you temporarily put it, is the purpose of the `tmp` variable. **However** note that in Python you don't have to use this technique and you can simply swap the items by `list2[i], list1[i] = list1[i], list2[i]`. So the code you've shown is actually a bad example. – mkrieger1 Oct 25 '18 at 22:02
  • 2
    Recommended reading to understand how this works in Python: https://nedbatchelder.com/text/names.html – mkrieger1 Oct 25 '18 at 22:09

0 Answers0