← Back to all snippets
PYTHON

Using `namedtuple` for Immutable, Readable Data Records

Create lightweight, readable, and immutable object-like data structures in Python using `collections.namedtuple` for cleaner code and structured data.

from collections import namedtuple

# Define a namedtuple for a Point
# A namedtuple creates a class-like object with named fields.
Point = namedtuple('Point', ['x', 'y'])

# Create instances of Point
p1 = Point(10, 20)
p2 = Point(x=30, y=40)

print(f"Point 1: {p1}")
print(f"Point 2: {p2}")

# Access elements by name or index (like a tuple)
print(f"P1 x-coordinate: {p1.x}")
print(f"P2 y-coordinate: {p2[1]}")

# Namedtuples are immutable (like tuples)
try:
    p1.x = 15 # This will raise an AttributeError
except AttributeError as e:
    print(f"Error trying to modify namedtuple: {e}")

# Useful for database records or API responses
User = namedtuple('User', 'id name email')
user1 = User(1, 'Alice Smith', '[email protected]')
user2 = User(id=2, name='Bob Johnson', email='[email protected]')

print(f"
User 1: {user1}")
print(f"User 1 Name: {user1.name}")

# Convert to dictionary
user_dict = user1._asdict()
print(f"User 1 as dictionary: {user_dict}")

# Replace fields (creates a new namedtuple instance)
user3 = user1._replace(email='[email protected]')
print(f"User 3 (replaced email): {user3}")
How it works: `collections.namedtuple` is a factory function for creating tuple subclasses with named fields. It allows you to create immutable, lightweight objects that are more readable than plain tuples (because you can access fields by name instead of index) but less memory-intensive than full custom classes. They are excellent for representing records from a database or API, returning multiple values from a function, or any situation where you need structured, fixed-field data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs