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.
1 2 3 4 5 6 7 8 9 10 | person = ('Matt', 70, 163) bmi = person[1]/(person[2]/100)**2 if bmi >= 18.5 and bmi <= 25: print("Healthy") elif bmi > 25: print("Overweight") else: print("Underweight") |
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)
1 2 3 4 | from collections import namedtuple Person = namedtuple('Person', ['name', 'weight_in_kgs', 'height_in_cm']) |
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:
1 | p1 = Person('Matt', 70, 163) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 | from collections import namedtuple Person = namedtuple('Person', ['name', 'weight_in_kgs', 'height_in_cm']) p1 = Person('Matt', 70, 163) bmi = p1.weight_in_kgs/(p1.height_in_cm/100)**2 if bmi>=18.5 and bmi<=25: print("Healthy") elif bmi > 25: print("Overweight") else: print("Underweight") |
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.
1 2 3 4 5 6 7 8 | from collections import namedtuple p1 = ['Frank', 25, 'German'] # First, we define a namedtuple Person = namedtuple('Person', ['name', 'age', 'nationality']) # using make() to convert list to namedtuple t1 = Person._make(p1) print(t1) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 | from collections import namedtuple # First, we define a namedtuple Person = namedtuple('Person', ['name', 'age', 'nationality']) # dictionary that we want to convert to a tuple d1 = {'name': 'Matt', 'age': 30, 'nationality': 'American'} # to convert into a namedtuple t1 = Person(**d1) print(t1) |
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.
Related posts
Today's pick
Categories
- Computer Vision/ML (3)
- Javascript (1)
- Linux (1)
- Python (20)
- Advance Python (3)
- Basic Python (6)
- Intermediate Python (11)
- Uncategorized (1)