Menu

Variables

Swapping Variables

To swap two variables means to exchange the values they hold, so the value stored in the first ends up in the second and the value in the second ends up in the first. Copying one variable straight into the other does not do this: one of the two values is lost at once.

Imagine a games club where two players' points totals were typed into the wrong variables and now need exchanging. Suppose scoreA = 458 and scoreB = 291. If you wrote scoreA = scoreB first, scoreA would hold 291 and the 458 would be lost for good. The next line, scoreB = scoreA, would then copy 291 into scoreB as well, so both variables would end up on 291 and one player's score would have vanished.

Save one value first

A temporary variable is a third variable that holds one value for a moment so that it is not overwritten. Copy scoreB into spare, copy scoreA into scoreB (safe now, because the 291 is saved), then copy spare into scoreA. The order matters: the copy into spare must happen before the variable it saves is overwritten.

StepAssignmentscoreAscoreBspare
Startnone458291not assigned
1spare = scoreB458291291
2scoreB = scoreA458458291
3scoreA = spare291458291

The temporary variable holds a value, not an index or a position: spare holding 291 is a copy of that score, not a note of where the score is stored. It simply keeps one value safe while the other variable is overwritten.

scoreA = 458
scoreB = 291

spare = scoreB   # keep scoreB's value before it is overwritten
scoreB = scoreA
scoreA = spare

print(scoreA)
print(scoreB)

Output:

291
458

Practise this