🎓 A1Learner
🔍

Python NamedTuple

A NamedTuple is a tuple with a name for each field. Code reads point.x instead of point[0].

A plain tuple first

A plain tuple gives each value a position only.

point = (3, 4)
print(point[0])
print(point[1])

Named fields

The class body lists each field. Each field gets a name and a hint.

from typing import NamedTuple

class Point(NamedTuple):
    x: int
    y: int

point = Point(3, 4)
print(point.x)
print(point.y)

Still a tuple

Indexing and unpacking still work. The record also equals a plain tuple.

from typing import NamedTuple

class Point(NamedTuple):
    x: int
    y: int

point = Point(3, 4)
print(point[0])
print(point == (3, 4))
x, y = point
print(x + y)

Defaults fill the tail

A field with a default can be left out. Defaults must sit after fields without defaults.

from typing import NamedTuple

class Point(NamedTuple):
    x: int
    y: int = 0

origin = Point(0)
home = Point(5)
print(origin)
print(home)

The older sibling

collections.namedtuple builds a record without hints. It is the older way to do the same job.

from collections import namedtuple

Color = namedtuple("Color", ["red", "green"])
color = Color(255, 0)
print(color.red)
print(color)

Example

from dataclasses import dataclass
from typing import NamedTuple


class Card(NamedTuple):
    rank: str
    suit: str


@dataclass
class CardData:
    rank: str
    suit: str


deck = [Card("A", "spades"), Card("K", "hearts"), Card("7", "clubs")]
for card in deck:
    print(card.rank, "of", card.suit)
data_card = CardData("A", "spades")
print(deck[0])
print(data_card)
print(tuple(deck[0]))
print(isinstance(deck[0], tuple))
print(isinstance(data_card, tuple))

Key points

  • NamedTuple: a tuple with a name for each field
  • Use typing.NamedTuple to define a record with type hints
  • Use collections.namedtuple to build a quick record without hints
  • Fields cannot change: a NamedTuple is immutable, like a tuple
  • Use a default value to fill a trailing field when it is left out
  • Use a dataclass instead when the record must change after creation
  • A NamedTuple is still a tuple in Python

In this example, Card is a NamedTuple with rank and suit fields. The deck holds three cards. The loop prints each card by field name. CardData is the dataclass version of the same record. Both records print with their field names. Only the NamedTuple is a tuple, so tuple() and isinstance show the split.

Note

You can index it and unpack it like one.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which fact about a NamedTuple is true?