collections.namedtuple
A factory, not a class: namedtuple() returns a new class whose instances are ordinary immutable tuples with names attached. Field names must be valid, non-keyword identifiers that do not start with an underscore.
Demo
from collections import namedtuple Point = namedtuple('Point', 'x, y z') Point._fields
Soft keywords such as match, case and type are allowed as field names; only hard keywords like class are rejected. rename=True replaces each bad name by an underscore plus its position, so the second "id" becomes _3 because it is the fourth field. _make needs exactly as many values as there are fields: TypeError: Expected 2 arguments, got 3.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| typename | str | yes | Name of the new class (shown in its repr). |
| field_names | str | iterable[str] | yes | Field names as a list, or one string separated by spaces and/or commas: 'x y' or 'x, y'. |
| rename | bool | no (False) | Replace invalid names with positional names _0, _1 … instead of raising ValueError. |
| defaults | iterable | None | no (None) | Default values for the RIGHTMOST fields. |
| module | str | None | no (None) | Sets __module__ of the new class (helps pickling). |
Return value
type — A new tuple subclass named typename.
Attributes
| Attribute | Type | Meaning |
|---|---|---|
| _fields | tuple[str, ...] | Field names, in order. |
| _field_defaults | dict | Field name → default value (3.7+). |
| _make(iterable) | classmethod | Build an instance from any iterable of exactly len(_fields) items. |
| _asdict() | method | A new dict mapping field names to values (a plain dict since 3.8). |
| _replace(**kw) | method | A new instance with some fields replaced; unknown names raise TypeError (3.13; ValueError before). |
Common patterns
from collections import namedtuple Stats = namedtuple('Stats', 'mean median') def stats(xs): return Stats(sum(xs) / len(xs), sorted(xs)[len(xs) // 2])
import csv from collections import namedtuple with open('data.csv', newline='') as f: reader = csv.reader(f) Row = namedtuple('Row', next(reader), rename=True) rows = [Row._make(r) for r in reader]
from collections import namedtuple Account = namedtuple('Account', 'owner balance', defaults=[0])
from typing import NamedTuple class Point(NamedTuple): x: float y: float = 0.0
Examples
Pitfalls
from collections import namedtuple Point = namedtuple('Point', 'x y') p = Point(1, 2) p.x = 5
from collections import namedtuple Point = namedtuple('Point', 'x y') p = Point(1, 2) p._replace(x=5)
from collections import namedtuple Bag = namedtuple('Bag', 'items', defaults=[[]]) a, b = Bag(), Bag() a.items.append(1) b.items
from collections import namedtuple Bag = namedtuple('Bag', 'items') a, b = Bag([]), Bag([]) a.items.append(1) b.items
from collections import namedtuple Point = namedtuple('Point', 'x y') Point(1, 2)._replace(z=3)
from collections import namedtuple Point = namedtuple('Point', 'x y') 'z' in Point._fields
When to use
- Small immutable records and function return values
- Tuples that are already passed around, made self-documenting
- Rows from CSV or database cursors
- Mutable records, validation, methods → dataclasses
- Type annotations on the fields → typing.NamedTuple
- A mutable attribute bag → types.SimpleNamespace
Notes
FAQ
A tuple subclass created by collections.namedtuple('Name', 'field1 field2'). Instances behave like normal tuples (indexing, unpacking, immutability) but also have named attributes and a readable repr such as Name(field1=1, field2=2).