Tuples are great! They allow you to store heterogeneous items in an ordered sequence. Also, when you want an immutable collection of items, tuples are the way to go.

However, tuples are not really your best friends when it comes to making your code readable. They tend to obfuscate the code, sometimes to a point that makes it unintelligible without a back-and-forth.

Let’s look at a simple example.

The above program calculates the BMI index of a person and prints whether they are healthy, overweight or underweight based on the BMI scale.

As we see the first statement, it is quite easy to say that the first item is the person’s name. But what about the other two items? It is very difficult to say quite exactly what they are, at least until we read the other statements. In the second line, we don’t really know what person[1] and person[2] means. There is got to be a cleaner solution.

One of the solution could be to create a class and assign the values to the attributes of the class. However, that would be a little complicated for this scenario. Could you think of other ways?

NamedTuple – to the rescue

NamedTuple is an elegant solution that Python provides for such a case. It is similar to a tuple except the attributes can be accessed by their names too, in addition to the indexes.

Let’s begin by seeing how a named tuple can be defined. (Please note that there are multiple ways to define a named tuple other than the one we are looking at. Check this out for other ways to define named tuple)

We just defined a namedtuple with the name ‘Person’ that has three attributes – ‘name’, ‘weight_in_kgs’ and ‘height_in_cm’.

To create a namedtuple object:

That’s it. We created a named tuple called ‘Person’. Now, let’s use it in our previous example and see how it affects our code.

Notice how profoundly it improves the readability of the code (especially line 6 where BMI is calculated). We know what the numbers 70 and 163 are. And most importantly, anyone could read and understand what is going on in line 6 without looking at the definition of tuple.

The __make() method

Consider you have a list, and you would like to convert it to a namedtuple. In this case, you make use of the __make() method.

You could also convert a dictionary into a namedtuple. But the keys of the dictionary should match the attributes of the tuple.

Let’s see an example.

You get the output:

Related : List vs. Tuple

*****

If you have any questions or comments regarding the post (or something else), please feel free to reach out through the comments.