all Python 3Tuples (tuple)term
Named tuple namedtuple
namedtuple
namedtuple creates a tuple class with named fields. The fields are reachable both by name and by index.
Syntax
from collections import namedtuple
NT = namedtuple('NT', ['field1', 'field2'])
It is still a tuple: you cannot assign to a field, and you build a modified copy with _replace(). The underscore in _replace, _asdict and _fields does not mean private — it keeps the method names from clashing with your own field names. A namedtuple compares equal to a plain tuple holding the same values, so == will not tell Point(1, 2) apart from (1, 2).
Examples
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p)
# → Point(x=3, y=4)
print(p.x, p.y)
# → 3 4
print(p[0], p[1])
# → 3 4 (доступ по индексу)
print(p._asdict())
# → {'x': 3, 'y': 4}
p2 = p._replace(x=10)
print(p2)
# → Point(x=10, y=4)
print(Point._fields)
# → ('x', 'y')
from collections import namedtuple
Card = namedtuple('Card', 'rank suit')
c = Card('A', 'spades')
print(f'{c.rank} of {c.suit}')
# → 'A of spades'
See also
Open in the full glossarydocs.python.orgReport an inaccuracy