On this page
collections.namedtuple
Prev: collections.deque | Up: collections | Next: collections.OrderedDict
Rel: collections.ChainMap, collections.Counter, collections.defaultdict, collections.deque
Ref: docs.python.org — collections.namedtuple
Tags: #public #python3 #stdlib #collections
Import
import collections
from collections import namedtuple
Signature & Overview
collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
Returns a new subclass of tuple with named fields.
Usage
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"], defaults=[0])
p = Point(3)
assert p == (3, 0) and p.x == 3 and p.y == 0
assert p._replace(y=4) == Point(3, 4)
Gotchas
- Immutable tuple subclass: Instances are memory-light, hashable, and unpackable like tuples, so fields cannot be reassigned in place (use
_replace()). - Prefer
typing.NamedTuplefor type annotations:class Point(NamedTuple): x: int; y: int = 0gives the same runtime tuple with clean static typing and IDE support.
REPL Inspect
from collections import namedtuple
help(namedtuple)
Linked from
Related notes
- tuts/python3/stdlib_module/collections/ChainMap Linked here; links to this page; shared tags: #collections, #stdlib
- tuts/python3/stdlib_module/collections/Counter Linked here; links to this page; shared tags: #collections, #stdlib
- tuts/python3/stdlib_module/collections/defaultdict Linked here; links to this page; shared tags: #collections, #stdlib
- tuts/python3/stdlib_module/collections/deque Linked here; links to this page; shared tags: #collections, #stdlib
- tuts/python3/stdlib_module/collections/OrderedDict Linked here; links to this page; shared tags: #collections, #stdlib
- tuts/python3/stdlib_module/collections Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/collections/UserDict shared tags: #collections, #stdlib
- tuts/python3/stdlib_module/collections/UserList shared tags: #collections, #stdlib
- tuts/python3/stdlib_module/collections/UserString shared tags: #collections, #stdlib
- tuts/rust/std/collections shared tags: #collections, #stdlib