#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. Tuple unpacking and intervals. So, what if you need to do a swap of variables? We got a and b are 1 and 2.
0:13
In other language you have to keep a temporary variable so you store a into tmp then you can override, a with b.
0:24
Then you can put the temporary variable back into b and now they're swapped. Right, so a now became 2 and b became 1.
0:32
Well in Python, it just takes one line of code. Let's restore them. Let's just do just swap them like this. And there you go.
0:49
No temporary variable needed. So that's step one, unpacking in action. Another example of that is the earlier max function returning two values.
0:58
Here we had legs 55 minutes, so you can assign them or tuple unpack them by assigning them to two variables. So in this case, routine and minutes.
1:12
There you go. A function that returns two values can just be unpacked by specifying an equal number of variables before the equal sign.
1:22
In this case, routine and minutes. N tuples, I will just do a quick demo because I already discussed them in more detail in a previous lesson.
1:35
That's not really saying that much because if I have to refer to them I would have to access them on day, what is that? The second?
1:47
Okay, so it's zero base so I do 1. I train, what do I train? Workout. Where's my training? Okay, it's the first element at 0.
2:03
Okay, at least I got that right. Okay, so if you do it that with n tuple. Let's create one with workout
2:21
equals workout with uppercase, which is the n tuple. I always uppercase, unless because I see them kind of as classes without behaviors
2:30
and classes you uppercase in Python. You can either give them an args list. You can also do that more verbose
2:50
with a keyword argument list. Now the print statement becomes a lot cleaner because I don't have to think about indexes. I can just do workout.day,
3:08
workout.routine, workout.duration, and it's much easier to type. It's much clearer to the reader of your code what you're actually referring to
3:22
and hence you'll probably make less mistakes. N tuples, they're very easy to define and use. It makes your code much more readable.
3:30
I would encourage you to use them whenever you can.