M&C4: Overwriting values in a swap operation

In applications rearranging data elements, it is common to exchange two values. This is known as the swap operation. A common beginner mistake is to write the code with two assignment statements resulting on one value being lost.  While this mistake can be made when just using variables, it happens more often when a list or an array is used.

A correct swap operation uses a temporary variable that holds the value of the first list element that will be overwritten. After the assignment to the temporary variable, first element can be overwritten by the second element. Finally, the second element gets the value in the temporary variable.

Example 1

# wrong swap operation
listA = [0, 1, 2]
listA[1] = listA[2]
listA[2] = listA[1]
print listA      # prints [0, 2, 2]

# correct swap operation
listB = [0, 1, 2]
temp = listB[1] # Use the variable temp to hold the value of listB[1]
listB[1] = listB[2]
listB[2] = temp
print listB     # prints [0, 2, 1]

Example 2

Bubble sort is a simple (and rather inefficient) way to sort elements in a list. Bubble sort iterates through the list repeatedly and compares two adjacent elements. If they are out of order, they are swapped. Eventually, no further swaps can be done and the list is sorted. For more on sorting algorithms, see post Example 8: Sorting.

The following Bubble Sort code does not correctly swap the elements and thus changes the entries in the list. Instead of generating the sorted list [-1, 2, 2, 3, 5], it generates the list [-1, -1, -1, 2, 2]. If your students have already seen loops, ask them to correct the code.

# Bubble Sort with incorrect swap operation
myData = [5, 3, -1, 2, 2 ]
i = 0

while i < len(myData) :
    j = 0

    while j < len(myData) - 1 :

        if myData[j] > myData[j+1] :
        myData[j] = myData[j+1]
        myData[j+1] = myData[j]
        j = j + 1
    i = i + 1

print myData
# final output expected: [-1, 2, 2, 3, 5]
# final output received: [-1, -1, -1, 2, 2]

Video Length: 2:43