← Back to all snippets
PYTHON

Creating Lightweight, Readable Data Records with Named Tuples

Discover how to use Python's `namedtuple` from the `collections` module to define simple, immutable object types with named fields, improving code readability and structure.

from collections import namedtuple

# Define a named tuple type for a Point
Point = namedtuple('Point', ['x', 'y'])

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

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

# Access fields by name or index
print(f"Point 1 X-coordinate: {p1.x}")
print(f"Point 2 Y-coordinate: {p2[1]}")

# Named tuples are immutable
try:
    p1.x = 15 # This will raise an AttributeError
except AttributeError as e:
    print(f"Attempting to modify p1.x failed: {e}")

# Convert to dictionary (useful for serialization)
p1_dict = p1._asdict()
print(f"Point 1 as dictionary: {p1_dict}")

# Named tuples are also iterable
x, y = p2
print(f"Unpacked Point 2: x={x}, y={y}")
How it works: A `namedtuple` from the `collections` module provides an easy way to create lightweight, immutable object types with named fields. It offers the readability of object-like access (e.g., `point.x`) while retaining the memory efficiency and immutability of tuples. They are excellent for defining simple data records, like coordinates or database rows, without the boilerplate of a full class.

Need help integrating this into your project?

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

Hire DigitalCodeLabs