Move from Excel to Python with Pandas Transcripts
Chapter: Appendix: Python language concepts
Lecture: Concept: Named tuples

Login or purchase this course to watch this video and the rest of the course contents.
0:01 In the previous section we discussed tuples, and how they are useful. Sometimes these anonymous tuples that we discussed are exactly what you need,
0:09 but oftentimes, it's very unclear what values are stored in them, especially as you evolve the software over time.
0:16 On the second line here, we have "m", a measurement we are defining this time it's something called a named tuple
0:22 and just looking at that definition there on what we are instantiating the measurement, it's not entirely clear the first value is the temperature,
0:29 the second value is the latitude, this third value is a longitude, and so on. And we can't access it using code that would treat it like a plain tuple,
0:37 here we say the temperature is "m" of zero which is not clear at all unless you deeply understand this
0:43 and you don't change this code, but because we define this as a named tuple, here at the top we define the type by saying
0:51 measurement is a collections.namedtuple, and it's going to be called a measurement, for error purposes and printing purposes and so on,
0:59 and then you define a string which contains all the names for the values.
1:03 So over here you are going to say this type of tuple temperature's first, then latitude,
1:07 then longitude, then quality, and what that lets us do is access those values by name. So instead of saying "m" of zero temperature,
1:14 we say m.temp is the temperature, and the quality is m.quality. Named tuples make it much easier to consume these results
1:21 if you are going to start processing them and sharing them across methods and things like that.
1:26 Additionally, when you print out a named tuple it actually prints a friendlier version
1:30 here at the bottom you see measurement of temperature, latitude, longitude, and quality.
1:34 So most of the time if you are thinking about creating a tuple, chances are you should make a named tuple.
1:40 There is a very small performance overhead but it's generally worth it.

Talk Python's Mastodon Michael Kennedy's Mastodon