Member-only story

Python NamedTuples: How They Help You to Write Readable Code

Erdem Isbilen
3 min readFeb 2, 2021

--

With easy to follow examples for beginners

Photo by Bench Accounting on Unsplash

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…

--

--

Erdem Isbilen
Erdem Isbilen

Written by Erdem Isbilen

Machine Learning and Data Science Enthusiasts, Automotive Engineer, Mechanical Engineer, https://www.linkedin.com/in/erdem-isbilen/

Responses (2)