Last modified: Jan 27, 2026 By Alexander Williams
Python Namedtuple Guide: Immutable Data Structures
Python's namedtuple is a powerful tool. It lives in the collections module. It creates tuple subclasses with named fields. This makes your code cleaner and more readable.
You get all the benefits of a regular Python tuple. This includes immutability and memory efficiency. But you also gain the ability to access data by attribute names, not just indices.
What is a Namedtuple?
A namedtuple is a factory function. It returns a new tuple subclass. The subclass has named fields. Think of it as a lightweight object. It is perfect for storing data records.
It is more memory-efficient than a regular class. It does not have a per-instance dictionary. This makes it faster to create and use. It is ideal for representing simple data.
Creating Your First Namedtuple
You start by importing it from the collections module. Then you call the namedtuple() function. You provide a type name and a list of field names.
# Import the namedtuple factory
from collections import namedtuple
# Create a 'Point' namedtuple type with fields 'x' and 'y'
Point = namedtuple('Point', ['x', 'y'])
# Create an instance of Point
p1 = Point(10, 20)
print(p1)
print(type(p1))
Point(x=10, y=20)
<class '__main__.Point'>
The output shows a readable representation. It includes the field names and their values. The instance p1 is of type Point, a subclass of tuple.
Accessing Data in a Namedtuple
This is where namedtuples shine. You can access data by index, like a normal tuple. You can also access it by the field name as an attribute. This makes code self-documenting.
# Using the Point namedtuple from before
p = Point(5, 12)
# Access by index (standard tuple behavior)
print(f"Index 0: {p[0]}")
print(f"Index 1: {p[1]}")
# Access by field name (namedtuple advantage)
print(f"Field x: {p.x}")
print(f"Field y: {p.y}")
# You can also use getattr
print(f"getattr for 'x': {getattr(p, 'x')}")
Index 0: 5
Index 1: 12
Field x: 5
Field y: 12
getattr for 'x': 5
Access by name is the key benefit. It makes your code much easier to understand. You no longer need to remember that index 0 is the x-coordinate. The code tells you directly.
Immutable and Unpackable
Like standard Python tuples, namedtuples are immutable. You cannot change a field's value after creation. This guarantees data integrity.
They also support tuple unpacking. This is very convenient for assignments and iterations.
# Immutability test
p = Point(1, 2)
try:
p.x = 99 # This will raise an AttributeError
except AttributeError as e:
print(f"Error: {e}")
# Tuple unpacking works perfectly
x_val, y_val = p
print(f"Unpacked: x={x_val}, y={y_val}")
# Useful in for loops
points = [Point(1, 2), Point(3, 4), Point(5, 6)]
for x, y in points:
print(f"Processing point at ({x}, {y})")
Error: can't set attribute
Unpacked: x=1, y=2
Processing point at (1, 2)
Processing point at (3, 4)
Processing point at (5, 6)
Useful Namedtuple Methods
Namedtuples come with several helpful methods. These methods make them even more practical for data handling.
The _asdict() method returns an OrderedDict. The _replace() method creates a new instance with some fields changed. The _make() method creates a new instance from an iterable.
Person = namedtuple('Person', 'name age city')
person = Person('Alice', 30, 'London')
# _asdict(): Convert to an ordered dictionary
person_dict = person._asdict()
print(f"As Dictionary: {person_dict}")
print(f"Dictionary type: {type(person_dict)}")
# _replace(): Create a new instance with updated fields
# Remember, the original is immutable
new_person = person._replace(age=31, city='Paris')
print(f"Original: {person}")
print(f"New: {new_person}")
# _make(): Create instance from a sequence or iterable
data = ['Bob', 25, 'Berlin']
person2 = Person._make(data)
print(f"Made from list: {person2}")
As Dictionary: {'name': 'Alice', 'age': 30, 'city': 'London'}
Dictionary type: <class 'dict'>
Original: Person(name='Alice', age=30, city='London')
New: Person(name='Alice', age=31, city='Paris')
Made from list: Person(name='Bob', age=25, city='Berlin')
When to Use Namedtuples
Namedtuples are excellent for specific scenarios. Use them when you need a simple, immutable data container. They are better than dictionaries when the field names are fixed and known.
They are perfect for representing database records, CSV rows, or configuration settings. They make your code more expressive than using plain tuples or lists. They are lighter than full classes when you don't need methods.
For more complex tuple manipulations, you might combine them with standard Python tuple operations.
Conclusion
Python's namedtuple is a fantastic feature. It bridges the gap between simple tuples and full classes. It provides immutability, memory efficiency, and readability through named access.
You should use it for data-centric tasks. It makes your code cleaner and less error-prone. You avoid magic indices. Your data structures become self-documenting.
Remember to import it from collections. Define your field names clearly. Then enjoy writing cleaner, more maintainable Python code.