#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.
0:03
We are all familiar with dict, list, set, and tuple.
0:05
The collections module
0:07
adds a few other specialized ones that are very useful.
0:12
Let's import the modules we're going to use.
0:20
A namedtuple is a convenient way
0:22
to define a class without methods.
0:24
We all familiar with a normal tuple,
0:28
which you can define with parenthesss,
0:30
and one or more elements.
0:35
The thing with the classic tuple,
0:36
though, is that the order is not
0:38
really meaningful, so if you print
0:43
the user name and the user role,
0:48
user index zero is a user index one,
0:54
and you already notice that the indexing
0:56
is not really saying that much.
0:59
Is there a more readable way
1:00
to define these kinds of tuples?
1:04
And yes, you can use a namedtuple, so let's define one.
1:08
User equals namedtuple, and you give it a name,
1:14
and the fields or arguments it takes, so name and role.
1:22
And let's create a user,
1:27
with user and I give it a name
1:32
Bob and role equals coder.
1:36
The nice thing, then, is that you can
1:38
access the entries like this, instead of
1:41
indexing with zero, one, etc.
1:44
So this is much more meaningful
1:49
And to see that in a print statement.
1:57
So, use namedtuples.
2:00
It's very easy to set up,
2:02
and it definitely makes your code more readable.