This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 2: Shortcut assignment statements

How to swap variables

face Josiah Wang

Did you manage to complete the swapping exercise?

Now, you might have tried the following as the first attempt. And it does not work.

x and y are both 24 after swapping.

x = 15
y = 24
x = y
y = x
print(x)
print(y)

What happened here was that I have already updated x to point to 24 in Line 3, and there is no longer a way for you to access the reference to 15!

Swapping  values of two variables

So, to be able to swap variables, you will need to introduce another variable to point to what x is pointing (15) first. Then you update x to point to what y is pointing to (24), then update y to point to what your temporary variable is pointing (15).

x = 15
y = 24
temp = x
x = y
y = temp
print(x)
print(y)

Swapping  values of two variables