Python Namedtuple: An Introduction to a Powerful Data Structure

Dr. Soumen Atta, Ph.D.
3 min readApr 7, 2023
Photo by Christopher Gower on Unsplash

Python is a popular high-level programming language that provides several built-in data structures to store and manipulate data efficiently. One such data structure is namedtuple, which is a subclass of tuple that allows you to give names to each element of the tuple. This tutorial will cover the basics of namedtuple in Python.

What is namedtuple?

Namedtuple is a subclass of tuple that provides named fields or attributes to the tuple elements. Each field can be accessed using a unique name, just like an attribute of an object. Namedtuple is defined in the collections module of Python.

Creating a namedtuple

To create a namedtuple, you need to import the namedtuple class from the collections module and define a new class that inherits from it. You can then define the field names as a comma-separated string, or as an iterable of strings.

Here’s an example:

from collections import namedtuple

# Defining a namedtuple class
Person = namedtuple('Person', ['name', 'age', 'gender'])

# Creating a namedtuple object
p1 = Person('John', 30, 'male')

# Accessing fields using names
print(p1.name) # Output: 'John'
print(p1.age) # Output: 30
print(p1.gender) # Output: 'male'

--

--

Dr. Soumen Atta, Ph.D.

I am a Postdoctoral Researcher at the Faculty of IT, University of Jyväskylä, Finland. You can find more about me on my homepage: https://www.soumenatta.com/