Named Tuple
In one line
namedtuple creates immutable, indexable records with named fields — lightweight alternative to dataclass.
In simple words
A namedtuple is a tuple where each position has a name. You access fields by name (p.x) or by index (p[0]), and it remains immutable and tuple-compatible.
Created via collections.namedtuple('Name', ['field1', 'field2']) or typing.NamedTuple subclass (with type hints). Named tuples use less memory than dataclasses and are ideal for lightweight immutable records.
They support unpacking (x, y = point), are hashable (usable as dict keys), and can be created with ._make() from iterables or ._replace() to create a modified copy.
Example
from collections import namedtuple
from typing import NamedTuple
# Classic style
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y) # 3 4
print(p[0]) # 3 (index access)
x, y = p # Unpacking
print(p._replace(x=10)) # Point(x=10, y=4)
# Type-hint style (Python 3.6+)
class Color(NamedTuple):
r: int
g: int
b: int
c = Color(255, 128, 0)
print(c) # Color(r=255, g=128, b=0)namedtuple gives named field access while remaining a real tuple — immutable, indexable, hashable, unpackable.
Common confusions
Confused with: dataclass
The difference: Named tuples are immutable, tuple-compatible (indexable), hashable, and memory-light. Dataclasses are mutable by default, support inheritance and methods easily, and are more flexible. Use namedtuple for simple immutable records, dataclass for richer behavior.
Related terms
Related Resources
Related Lessons
- Python Data Structures
Named tuples.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.