Python comes with many specialised data types. In this article, I will try to explain NamedTuples by providing easy-to-follow examples for the beginners.
NamedTuple is basically an extension of the Python built-in tuple data type. Here is how doc.python.org defines the NamedTuples;
Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index
To understand NamedTuples further, let’s first recall what the Python tuples are.
Python tuples are;
a_tuple = tuple()
a_tuple = (1,2,3,4,5)
print (a_tuple[2]) #accessing the element with only positional index
a_tuple[0] = 10 #tuples are immutable so you can not revise them
Output:
3
TypeError: 'tuple' object does not support item assignment
The downsides of the tuples;
Let’s understand how NamedTupes solve these issues in the following chapter.
#python #data-structures #tuples