DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on

Python Named Tuple

A named tuple in python is a subclass of tuples. The named tuple has the same functionalities as a normal tuple, but its values can be accessed both by name (using dot notation eg: .name) as well as by position (offset notation eg: [0]). In this blog, we will learn what is Named Tuple in python, its syntax, and functions with the help of examples.

Why Do We Need Namedtuple In Python?

One obvious question that will be on your mind is, “Why do we need Named Tuple in Python when we have a standard tuple?“.

The response to this question is that the named tuple improves the readability of the code and functions as a self-documented code.

Let’s understand it via an example:

Suppose we are setting up a software that stores student subject marks in a tuple called ‘marks.’ But, this code is readable only when the tuple description is in our memory. We are likely to forget the tuple definition after two or three days.

Python Tuple

marks = (98, 80, 95)
print(marks)
print(marks[0])
print(marks[2])
(98, 80, 95)
98
95
Enter fullscreen mode Exit fullscreen mode

Named Tuple comes as a substitute for the regular tuple, which functions the same as the usual tuple, but improves the readability of our code. And even if the creator takes a break of one or two months, the syntax or meaning of the named tuple will speak for itself.

That’s what we need as a developer, a self-documented code.

Enough talking about Named Tuple. It’s high time to introduce you to its syntax.

Learn about Python Named Tuple from the Original Post.

Top comments (0)