#100DaysOfCode in Python Transcripts
Chapter: Days 34-36: Refactoring / Pythonic code
Lecture: Refactoring 5: tuple unpacking and namedtuples

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Next up, refactoring 5.
0:02 Tuple unpacking and intervals.
0:04 So, what if you need to do a swap of variables?
0:07 We got a and b
0:10 are 1 and 2.
0:12 In other language you have to keep
0:14 a temporary variable so you store a into tmp
0:18 then you can override, a with b.
0:23 Then you can put the temporary variable
0:24 back into b and now they're swapped.
0:27 Right, so a now became 2 and b became 1.
0:31 Well in Python, it just takes one line of code.
0:35 Let's restore them.
0:39 Let's just do
0:43 just swap them like this.
0:46 And there you go.
0:48 No temporary variable needed.
0:49 So that's step one, unpacking in action.
0:51 Another example of that is the
0:53 earlier max function returning two values.
0:57 Here we had legs 55 minutes, so you can assign them
1:02 or tuple unpack them by assigning them to two variables.
1:06 So in this case, routine and minutes.
1:11 There you go.
1:12 A function that returns two values can
1:15 just be unpacked by specifying
1:18 an equal number of variables before the equal sign.
1:21 In this case, routine and minutes.
1:23 N tuples, I will just do a quick demo
1:26 because I already discussed them
1:28 in more detail in a previous lesson.
1:34 That's not really saying that much
1:35 because if I have to refer to them
1:37 I would have to access them on
1:43 day, what is that?
1:45 The second?
1:46 Okay, so it's zero base so I do 1.
1:49 I train, what do I train?
1:52 Workout.
1:55 Where's my training?
1:56 Okay, it's the first element at 0.
2:02 Okay, at least I got that right.
2:06 Okay, so if you do it that with n tuple.
2:15 Let's create one with workout
2:20 equals workout with uppercase, which is the n tuple.
2:24 I always uppercase, unless because I see them kind
2:27 of as classes without behaviors
2:29 and classes you uppercase in Python.
2:31 You can either give them an args list.
2:45 You can also do that more verbose
2:49 with a keyword argument list.
2:56 Now the print statement becomes a lot cleaner
2:59 because I don't have to think about indexes.
3:01 I can just do workout.day,
3:07 workout.routine,
3:11 workout.duration, and it's much easier to type.
3:17 It's much clearer to the reader of your code
3:19 what you're actually referring to
3:21 and hence you'll probably make less mistakes.
3:24 N tuples, they're very easy to define and use.
3:27 It makes your code much more readable.
3:29 I would encourage you to use them whenever you can.