#100DaysOfCode in Python Transcripts
Chapter: Days 4-6: Collections module
Lecture: Namedtuples: more readable code
Login or purchase this course to watch this video and the rest of the course contents.
0:00 Get Pythonic with a collections module. We are all familiar with dict, list, set, and tuple. The collections module
0:08 adds a few other specialized ones that are very useful. Let's import the modules we're going to use. A namedtuple is a convenient way
0:23 to define a class without methods. We all familiar with a normal tuple, which you can define with parenthesss, and one or more elements.
0:36 The thing with the classic tuple, though, is that the order is not really meaningful, so if you print the user name and the user role,
0:49 user index zero is a user index one, and you already notice that the indexing is not really saying that much. Is there a more readable way
1:01 to define these kinds of tuples? And yes, you can use a namedtuple, so let's define one. User equals namedtuple, and you give it a name,
1:15 and the fields or arguments it takes, so name and role. And let's create a user, with user and I give it a name
1:33 Bob and role equals coder. The nice thing, then, is that you can access the entries like this, instead of indexing with zero, one, etc.
1:45 So this is much more meaningful And to see that in a print statement. So, use namedtuples. It's very easy to set up,
2:03 and it definitely makes your code more readable.