This lesson accounts for why a namedtuple was introduced by Python, and how to use it.

Introduction

A namedtuple is another container sequence but an extended version of the built-in tuple sequence. It is also an immutable sequence. The question is: why was there a need to extend the tuple in the first place? Let us explore the mystic details of this container.

Why use a namedtuple?

Python makes it easy for the developers to make a class manually by introducing this container. It makes debugging easy. By the end of this lesson, you will get why this extension was planned.

⚙️ Note: Namedtuples were added to the standard library in Python 2.6 for the first time.

Limitations of a tuple

There must be something missing in tuples, which is why namedtuples hold a special place. You know by now that:

  • We can only access data from a tuple by using an index (that is not a human-readable identifier).
  • Secondly, there is no guarantee that tuples that are supposed to hold the same type of values will do so. You can easily make a list of tuples containing different types of values. It makes debugging difficult.

Creating a namedtuple

It is called namedtuple because a human-readable identifier can access each field in it. For example:

from collections import namedtuple #Importing the extended sequence

Fruit = namedtuple('Fruit', 'name color price')

So here’s the main thing, do not confuse the structure of tuple with a namedtuple. Its structure is slightly different to overcome the limitations discussed above. Here, namedtuple is a function that takes two parameters:

  • The typename: Fruit
  • The field_names: name, color, and price.

Field names get split at the backend at the whitespace character. We can pass the name of the fields in the form of a list for the sake of readability; otherwise, passing field names in a single string (with whitespace as a separator) works fine.

Now, we are good to create new fruit objects with the Fruit factory function. Run the example below.

Get hands-on with 1200+ tech skills courses.