Swapping Variables in Place
Swapping the contents of two variables is a tedious task in most languages because it usually involves introducing a third temporary variable that stores the contents of one of the other two variables while their contents are being shifted around.
In this lesson you learned how simple it is to swap variables in place using Python tuples:
mahdi, tina = tina, mahdi
00:00
Next, we’re going to discuss swapping. Now this here is usually a little bit of a tedious task in other languages where you have to assign one of the variables to a temp
and then assign the other variable to the first one that you assigned to the temp
, and then assign temp
to the variable that you did the first assign on.
00:25
we did something like this this. That resulted in mahdi
being assigned to temp
, tina
being assigned to mahdi
, temp
being assigned to tina
.
00:35 In Python, there’s an easier way to do this and much cleaner and much more precise.
00:43
We simply use tuple unpacking, and that will result in the same step here. Often, people think tuples are denoted by the brackets that contain them. So for example, if we had ('dog', 'cat')
,
01:00
the tuple isn’t created by the smooth braces, but rather the comma in between the statements. So the statement above goes “Assign this tuple to that tuple in piecewise order.” So assign tina
to mahdi
and mahdi
to tina
, and then the result prints the flipped version of things.
Become a Member to join the conversation.