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