Namedtuple in Python
Tags: python, namedtuple, tutorial, example
Published: 2019-10-20 05:50:10

_Cross posted from [Rakesh's Blog](http://rakeshgautam.com/posts/namedtuple-in-python/)_

To understand NamedTuple, you first have to understand what a regular Tuple in Python is.

### What is a Tuple

A Tuple in Python is similar to a List. The difference between a Tuple and a List is that the Tuples are Immutable, which means that you can't change the elements of a Tuple once it is assigned.

The other difference is that the Tuples are defined using parentheses `()` instead of square brackets `[]` in a list.

Tuples are also indexed with Integers, like List. To access a value in a tuple, you have to provide its numeric index.

### What is Namedtuple

As the name suggests, Namedtuples are just Tuples but with Names assigned to its elements.  NamedTuples can do everything that a Tuple can do. But the advantage of NamedTuples over Tuple is that you can access its values using the numeric index as well as the Names preassigned to its fields.

When the number of elements is large, it becomes hard to remember which index is what. So namedtuple comes handy in that situation with all the features of a Normal Tuple and an added feature of accessibility with field names.

This problem can also be solved by creating a class with read-only properties and accessing values by `classname.fieldname`. But a class seems Overkill for this purpose. With Namedtuples, we avoid all the code for a class and still can access the values like `record.fieldname`.

You can still use the index number to access the values stored. So namedtuple is like a compromise between a Tuple and a List/Dictionary in Python.

### How to create a Namedtuple

Namedtuple is present in the `collections` module of Python.

    >>> from collections import namedtuple
    >>> Person = namedtuple("Person", "name age sex")
    >>> person1 = Person("Rakesh", 24, "male")

Each namedtuple is represented by its own class, created by using the `namedtuple()` factory method. The first argument is the name of the new class/namedtuple and the second argument is a string containing the names of the elements, separated by spaces or commas.

After creating the structure and providing values to the namedtuple as shown in the above code block, you can use the dot notation to access the values in our Person namedtuple.

    >>> print(person1.name)
    Rakesh
    >>> print(person1.age)
    24
    >>> print(person1.sex)
    male

The values can also be accessed using the numeric index like the regular tuples and lists.

    >>> person1[0]
    'Rakesh'
    >>> person1[1]
    24
    >>> person1[2]
    'male'

Both above code blocks provide the same output, but with different access methods. So you can use whichever notation you find useful.

### Attributes of a Namedtuple

#### _fields

Use this to get the field names of all the items in a namedtuple.

    >>> person1._fields
    ('name', 'age', 'sex')

#### _replace

Namedtuple is immutable but we can use this `_replace` which returns a shallow copy of the namedtuple, with specified property values changed. The original namedtuple stays unchanged.

    >>> person1._replace(name="Gautam")
    Person(name='Gautam', age=24, sex='male')

#### _asdict

This returns the contents of a namedtuple as an ordered dictionary.

    >>> person1._asdict()
    OrderedDict([('name', 'Rakesh'), ('age', 24), ('sex', 'male')])

The above code returns person1 namedtuple as an OrderDict, in the order, they were added.

#### _make

This can be used to create an instance of a namedtuple from a sequence or iterable. It comes handy when you have to create a Namedtuple from Existing data.

    >>> p2 = ["Eli", 21, "male"]
    >>> person2 = Person._make(p2)
    >>> person2
    Person(name='Eli', age=21, sex='male')

### Benefits of using Namedtuples

- You can access values using the names of the fields as well as the indexes.
- Namedtuples are as memory efficient as regular Tuples because it does not have per-instance dictionaries. This is also why it is faster than a dictionary.
- Improves the readability of your code.

So, hopefully, this kind of clears what a Namedtuple is and how it can be used to improve the readability and to write clean code.