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.

What is ‘NamedTuple’ Data Type?

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;

  • immutable objects: values inside a tuple object cannot be revised after creation.
  • sequence type data structures that allow accessing items contained with the 0-based integer positional index.
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;

  • You can access the elements of tuple only with the positional index. If you need to get a specific item from a tuple object, you should know the index number of that specific item. In addition, using indexing in such cases will harm the readability of your code.
  • While using tuples to store data that a function returns, you have to ensure the correct order of the elements.

Let’s understand how NamedTupes solve these issues in the following chapter.

#python #data-structures #tuples

Python NamedTuples: How They Help You to Write Readable Code
2.15 GEEK