From the course: Advanced Python (2018)

Unlock the full course today

Join today to access over 24,000 courses taught by industry experts.

Using namedtuple

Using namedtuple

- Let's start by looking at the namedtuple. Now some people say toople, some people say tuple. Tomato, tomato, it doesn't really matter. I call them tuples. Now, suppose I wanted to define a data structure to represent a geometric point on a typical x and y axis. Now, I could easily do this by defining a regular tuple with two elements, the x and y values of the point. Now, to access these values I can use positional argument indexes to get each one. Now, this may seem all fine and good, but as my program becomes more complex this kind of code easily looses its meaning and becomes hard to read. Especially, if I don't keep the names of all the point variables clear and meaningful. And maybe you can do it on your own, but your colleagues might not do it, so the code could get pretty hard to read after awhile. Now, I could just define a Python class and give it member properties for x and y and then write getattr and setattr functions and so on, but that seems a little much for a…

Contents