Compact structured records
Representing a small fixed-shape record returned by a function or parsed from input.
Python · Class
namedtuple() builds tuple subclasses with readable named fields. The resulting records remain indexable and iterable like tuples while also supporting attribute access.
namedtuple() creates a tuple subclass whose instances retain tuple behavior while exposing declared fields as attributes. Field names may be supplied as a sequence or as a whitespace- or comma-separated string; optional defaults fill trailing fields when values are omitted.
collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)| Name | Type | Description |
|---|---|---|
typename | str | Name for the generated tuple subclass. |
field_names | sequence[str] | str | Field names as a string sequence or whitespace- and/or comma-separated string. |
rename | bool | If true, replace invalid or duplicate names with valid generated names. |
defaults | iterable | Defaults for omitted rightmost fields. |
module | str | Value assigned to the generated type's __module__ attribute. |
A new tuple subclass named typename, with the declared fields available by attribute lookup as well as indexing and iteration.
from collections import namedtuple
Point = namedtuple("Point", "x y", defaults=[0])
point = Point(3)
assert point.x == 3
assert point.y == 0
assert point[0] == 3
assert point._fields == ("x", "y")
print(point)Creates a tuple-compatible Point type with named fields and a default for y, then accesses the result by attribute and index.
Representing a small fixed-shape record returned by a function or parsed from input.
Passing records through code that expects tuples while making individual fields readable.
Providing readable values in logs, debugging sessions, and interactive inspection.
It returns a new tuple subclass named by typename. Instances can be indexed and iterated like tuples, while also supporting attribute access for their declared fields.
Follow-up: Why might namedtuple be preferable to a dictionary for a fixed record? It preserves compact tuple behavior and positional compatibility while making field access self-documenting.
field_names can be a sequence of strings or one string whose names are separated by whitespace and/or commas. Each name must be a valid Python identifier and cannot start with an underscore.
Follow-up: How can malformed names be handled? Set rename=True to replace invalid or duplicate names automatically, then check the generated field names.
defaults supplies default values for omitted trailing fields, and module can set the generated type's __module__ attribute. The signature makes both options keyword-only after field_names.
Follow-up: Which fields receive defaults? The defaults correspond to the rightmost fields, so omitted values must form a suffix of the field list.
tuplecollections.OrderedDictcollections.defaultdictcollections.deque