Write Pythonic Code Like a Seasoned Developer Transcripts
Chapter: Tuples
Lecture: Swapping values
Login or
purchase this course
to watch this video and the rest of the course contents.
0:01
Let's see the Pythonic way to swap two values and hint: It involves tuples. All right, so here we have two values, "x" and "y",
0:09
you can see we'll print them out here and we'll print them out there and our attention is to do some sort of swap thing.
0:14
Let's just run it really quickly. All right, obviously not swapped yet, let's swap them here. In most languages, this is sort of a 3-step process,
0:21
you'd say something like "temp = x", "x = y", "y = temp". Now if we run this, you'll see they should be swapped,
0:28
great, 7, 11, 11, 7, but this is non-Pythonic. And let's even teach PyCharm: "Hey, that's a word".
0:38
OK, so if we are going to do this in a Pythonic way, we are going to use tuples, and it turns out you can do it in a beautiful concise one-liner
0:46
by temporarily creating a tuple and then unpacking it into the same variables but in reverse, so we can say "y, x = x, y".
0:55
Remember, the comma here creates a tuple and then the stuff in the left hand side will unpack that tuple
1:00
back into the values but it unpacks "x" into "y" and unpacks "y" into "x". Beautiful, one line, very Pythonic, let's see if it works.
1:08
Ta da, same thing, much cleaner. Want to swap two values in Python? Create a tuple and unpack it back into the reversed set of variables,
1:18
so here we have "x" and "y", we say "y, x = x, y". Swapped, one line, very Pythonic.