Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

In-Place Variable Swapping

Give Feedback

Here’s a code snippet showing the example code used in this lesson:

peter = 0
muira = 1

print(peter, muira)


# Bad: Using a temp variable

# temp = muira
# muira = peter
# peter = temp

# print(peter, muira)


# Good: Tuple Unpacking

peter, muira = muira, peter

print(peter, muira)

00:00 In this lesson, I want to show you how you can swap the values of variables in Python using tuple unpacking. So, first, let’s start off. You have two variables here.

00:11 One is peter, one is muira, and they have each a number assigned to them. So if you print that out, you’re going to get 0 1.

00:17 And then you want to swap these two variables so that muira points to 0 and peter points to 1. Now, in many languages, you have to do this using a temp variable.

00:27 So first, you assign the value of muira to temp, then the value of peter to muira, and then the value of temp finally to peter.

00:35 And at that point, you would have the two values of the variables swapped. Let me show you this by running it. You can see that you get 0 1 at first by printing peter, muira. And then we have the same print() function call here, and you get the opposite, so the variables were swapped. Now this works, as you can see, but in Python, there is a more idiomatic way of doing this,

01:02 which is by tuple unpacking. So instead of doing this whole temp variable thing, what you can do is say peter, muira = muira, peter. And by that, Python implicitly creates a tuple here, which is defined by the comma in between. You don’t actually need to use the brackets to create a tuple. The comma is the important part.

01:24 It creates this tuple here and then unpacks it by assigning the first value of the tuple to the first variable here and the second value of the tuple to the second variable here.

01:35 And with this one-liner statement, you have achieved the same thing as you did up there with the temp variable, and you’ve successfully swapped the two values of the two variables.

01:45 So, let’s run it just to show the output. First, it was 0 1, and after swapping the variables, you get 1 0. This is a very idiomatic and Pythonic way of swapping variables in Python.

Become a Member to join the conversation.