Python Namedtuple: An Introduction to a Powerful Data Structure
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'