PYTHON

Creating Lightweight Objects with namedtuple

Use collections.namedtuple to create memory-efficient, immutable record types with readable field names instead of standard tuples or classes.

from collections import namedtuple

# Define a namedtuple type
Point = namedtuple("Point", ["x", "y"])

# Instantiate the object
p = Point(x=10, y=20)

# Access by name or index
print(p.x)
print(p[1])
How it works: namedtuple assigns names to each position in a tuple, resulting in self-documenting code. They are memory-efficient because they don't use dictionary-based attribute lookups like regular classes, yet they offer clean dot-notation property access.

Need help integrating this into your project?

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

Hire DigitalCodeLabs