What
-
A NamedTuple is a lightweight, immutable data structure in Python that allows you to create
tuple-like objects with named fields. It provides a way to create simple, memory-efficient classes with named attributes.
NamedTuples combine the best of tuples (immutability, performance) and dictionaries (named access) while maintaining a lightweight, memory-efficient structure.
from collections import namedtuple
# Creating a NamedTuple
Person = namedtuple('Person', ['name', 'age', 'city'])
# Instantiating a NamedTuple
john = Person(name='John Doe', age=30, city='New York')
# Accessing fields
print(john.name) # Outputs: John Doe
print(john.age) # Outputs: 30