Python Reference ยท Standard Library: Data Structures and Functional Tools
collections.namedtuple
Reference for Python collections.namedtuple: tuples with named fields, _replace, _asdict, _make, defaults, rename and when to prefer dataclasses.
namedtuple() is a factory: it builds a new tuple subclass whose positions also have names. Instances still behave like tuples (indexing, unpacking, immutability, hashing) but you can read fields as attributes, which makes code self-explaining.
Memory use is about the same as a plain tuple, and there is no per-instance __dict__.
from collections import namedtuple Point = namedtuple("Point", ["x", "y"]) p = Point(3, 4) print(p.x, p[1])
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
| Name | Description |
|---|---|
typename |
Name of the new class. |
field_names |
A list of strings, or one string separated by spaces and/or commas. |
rename |
If True, invalid or duplicate names are replaced with _0, _1, ... by position. |
defaults |
An iterable of default values, applied to the rightmost fields. |
module |
Value for the class's __module__; useful for pickling classes created in a factory. |
| Class member | Description |
|---|---|
_make(iterable) |
Class method: build an instance from an iterable. |
_asdict() |
Return a regular dict mapping field names to values. |
_replace(**kwargs) |
Return a new instance with some fields changed. |
_fields, _field_defaults |
Tuple of field names; dict of defaults. |
Return value: a new class, not an instance. Calling it with positional or keyword arguments creates instances.
Raises: ValueError for invalid or duplicate field names (without rename), names starting with an underscore, or Python keywords; TypeError for wrong argument counts when instantiating; AttributeError when assigning to a field.
Usage notes
- Immutable. You cannot assign to fields.
_replace()returns a changed copy, and the original stays as it was. - Equal to plain tuples.
Point(1, 2) == (1, 2)isTrue, and two different namedtuple types with equal values compare equal too. That can surprise you in tests. - Underscore prefixes on
_replace,_asdictand friends prevent clashes with your field names; they are public API despite the underscore. - Prefer
typing.NamedTuplewhen you want type hints, docstrings, methods and defaults in class syntax. - Choosing a type: use a namedtuple for small, immutable, tuple-compatible records. Use a
dataclasswhen you need mutability,__post_init__, inheritance or non-tuple behavior. - Field order matters for positional creation, unpacking and comparison (ordering compares field by field).
- Pickle-friendly when the class is assigned to a module-level name matching
typename. - Repr shows field names, which makes logs readable:
Point(x=3, y=4).