Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

collections.namedtuple

Generates a tuple subclass with named fields and positional tuple behavior.

Version: Python 3.14; repository image, production runtime not attested

Syntax

collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)

Generates a tuple subclass with named fields and positional tuple behavior.

A replacement operation returns a new instance because the original tuple fields are immutable.

The factory returns a new tuple subclass. Construct its instances by position or by field name. The example's p.x and p[1] access the two coordinates, and _replace produces a new Point. Defaults apply to the rightmost fields. With rename=True, duplicate or invalid field names are replaced by positional names such as _1.

from collections import namedtuple
Event = namedtuple("Event", ["kind", "count"], defaults=[1])
ev = Event("click")
assert tuple(ev) == ("click", 1) and ev.count == 1
assert ev._replace(count=2).count == 2 and ev.count == 1
assert namedtuple("T", ["x", "x"], rename=True)._fields == ("x", "_1")

Examples

import collections
Point = collections.namedtuple("Point", "x y")
p = Point(2, 5)
print(p.x, p[1])
print(p._replace(x=9), p)

Result

2 5
Point(x=9, y=5) Point(x=2, y=5)

The factory returns a new tuple subclass. Construct its instances by position or by field name. The example's p.x and p[1] access the two coordinates, and _replace produces a new Point. Defaults apply to the rightmost fields. With rename=True, duplicate or invalid field names are replaced by positional names such as _1.

Sources