Python namedtuple Syntax & Function with Example

Python namedtuple, syntax and functions with example
Share this blog with others!
  • 1
    Share

A namedtuple 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.

marks = (98, 80, 95)
print(marks)
print(marks[0])
print(marks[2])
(98, 80, 95)
98
95

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 taking about Named Tuple. It’s high time to introduce you to its syntax.

Import namedtuple in python

Like other python data structures (List, Dict, Tuple and Set), Named Tuple is not supplied with python. We need to import it from a module that holds namedtuple.

The Named Tuple in Python is defined in a library called ‘collections‘, which provide alternatives to the python general-purpose in-built data structures.

from collections import namedtuple

Now, when we’ve imported the namedtuple from the Collections Library, we can use it and learn the syntax and functions of the namedtuple.

Python Named Tuple Syntax

collections.namedtuple(typenamefield_names*rename=Falsedefaults=Nonemodule=None)

The above code is taken from the python official documentation.

Let’s create a named tuple.

Python namedtuple Creation

In the previous sections, we imported the namedtuple and took a look at the syntax.

from collections import namedtuple

Marks = namedtuple('Marks', 'Physics Chemistry Math CS')
marks = Marks(90, 85, 95, 100)
print(marks)
Marks(Physics=90, Chemistry=85, Math=95, CS=100)

First of all we define the namedtuple signature, the first parameter takes the type name and the second takes the field names.

Type name is a string value that you want to define as namedtuple.

Learn How to generate iterators using Python Generator.

The name of the field may be an iterable data structure, such as list, dict, tuple, or set.

In the case of a string, the name of the field is split using the space as a delimiter.

marks = Marks(90, 85, 95, 100) – This creates marks as a named tuple. ‘Marks’ is used as a namedtuple definition and can be used to create an infinite number of named tuples, also called a factory of named tuples.

The positional arguments are mapped to the namedtuple definition.

For the sake of readability you can create named tuples using the keywords. – marks = Marks(Physics=90, Chemistry=85, Math=95, CS=100)

Create namedtuple using List

lst = ['Physics', 'Chemistry', 'Math', 'CS']
Marks = namedtuple('Marks', lst)
marks = Marks(90, 85, 95, 100)

>>> print(marks)

Marks(Physics=90, Chemistry=85, Math=95, CS=100)

Python namedtuple Using Dict

The initial value of in the dictionary is 0 as the value field is ignored by the namedtuple.

dct = {'Physics': 0, 'Chemistry': 0, 'Math': 0, 'CS': 0}
Marks = namedtuple('Marks', dct)
marks = Marks(90, 85, 95, 100)

>>> print(marks)


Marks(Physics=90, Chemistry=85, Math=95, CS=100)

Named Tuple in Python using Tuple

tupl = ('Physics', 'Chemistry', 'Math', 'CS')
Marks = namedtuple('Marks', tupl)
marks = Marks(90, 85, 95, 100)

>>> print(marks)

Marks(Physics=90, Chemistry=85, Math=95, CS=100)

Named Tuple using Set

subject_set = {'Physics', 'Chemistry', 'Math', 'CS'}
Marks = namedtuple('Marks', subject_set)
marks = Marks(90, 85, 95, 100)

>>> print(marks)
Marks(Physics=90, Chemistry=85, Math=95, CS=100)

You can create named tuple using any data structure that can be iterated.

Creating Named Tuple in Python using the _make function

In the previous section, we learned how to create a named tuple using any iterable data structure in python. In this section, we will learn how we can create a named tuple using the _make function.

lst = ['Physics', 'Chemistry', 'Math', 'CS']
Marks = namedtuple('Marks', lst)
marks = Marks._make([55, 78, 98, 90])

>>> print(marks)

Marks(Physics=55, Chemistry=78, Math=98, CS=90)

The _make function also takes an iterable (In Dictionary the key is taken as value).

marks = Marks._make({55: 'Physics', 78: 'Chemistry', 98: 'Math', 90: 'CS'})

>>> print(marks)

Marks(Physics=55, Chemistry=78, Math=98, CS=90)

Access Python namedtuple Field Names

We learned how to create a named tuple in python. Now its time to learn how we can access the field names from the named tuple.

There are two ways to access the field names from a named tuples:

  1. Offset Notation
  2. Dot Notation
  3. getattr()

We can access the field names as we used to do it in tuple, using the offset.

print(marks[0])
print(marks[3])

We can also access field names, just as we can access the attributes of a class from its instance.

print(marks.Physics)
print(marks.CS)

The Field names can also be accessed using the getattr() function.

print(getattr(marks,'Physics'))
print(getattr(marks,'CS'))
90
100

Python Named Tuples are Immutable

Just like Standard Tuples in Python, Named Tuple is also immutable in nature, means once the named tuple is declared its field’s values can’t be changes.

Example:

>>> marks.Physics = 99

File ".\main.py", line 6, in <module>
    marks.Physics = 99
AttributeError: can't set attribute

Replace Python namedtuple Field Value

In the above example, we saw the immutable nature of the named tuple. But there is a way in which we can change the value of the field name.

This can be done using the _replace function.

marks = marks._replace(Physics=99)

>>> print(marks)

Marks(Physics=99, Chemistry=78, Math=98, CS=90)

The _replace() function takes the field name and the value that is to be replaced and returns a new namedtuple with the changed value, hence we made Python namedtuple mutable using a simple trick.

Hope you like this article!

Also learn about other python tutorial articles like python list comprehension, Inner Function, Anonymous/Lambda Function, Custom Exception etc.


Share this blog with others!
  • 1
    Share

Leave a Comment

Your email address will not be published. Required fields are marked *