Search⌘ K
AI Features

Namedtuple: An Extension of Tuple

Explore how namedtuple improves upon the traditional tuple by adding named fields for better readability and debugging. Understand how to create namedtuples, access their fields, and use their special methods. This lesson helps you grasp the advantages of namedtuples as immutable containers and their practical applications in Python code.

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