Python › Dataclasses & NamedTuples

How do you create a simple immutable record using collections.namedtuple?

Beginner

Answer

namedtuple(typename, field_names) creates a NEW tuple subclass whose elements can be accessed both by INDEX (like a regular tuple) and by NAMED ATTRIBUTE, combining a tuple's lightweight immutability with readable, self-documenting field access.
from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)
print(p.x, p.y)   # 1 2 -- named attribute access
print(p[0], p[1]) # 1 2 -- also works like a regular tuple
Real-world example Representing a simple, lightweight, immutable record (like a coordinate or RGB color) without the overhead of a full class.

Common follow-ups: How does namedtuple compare to a regular tuple in terms of memory usage?