PythonMastery

namedtuple in Python

Create a namedtuple so each item of a tuple has a name: p.x instead of p[0]. Also _replace(), _asdict() and the typed NamedTuple form.

A namedtuple is a tuple whose items also have names. You can read a field as p.x instead of p[0], which makes the code easier to read.

The program

python
from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])

p = Point(3, 4)
print(p)
print(p.x, p.y)
print(p[0], p[1])

distance = (p.x ** 2 + p.y ** 2) ** 0.5
print("Distance from (0, 0):", distance)

x, y = p
print(x + y)
output
Point(x=3, y=4)
3 4
3 4
Distance from (0, 0): 5.0
7

How it works

Changing a field, and converting to a dict

python
from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)

moved = p._replace(x=10)
print(moved)
print(p)
print(moved._asdict())
output
Point(x=10, y=4)
Point(x=3, y=4)
{'x': 10, 'y': 4}

_replace() returns a new tuple and leaves the original unchanged. _asdict() returns a normal dictionary. The underscore at the start of these names stops them from clashing with your own field names.

The typed form

typing.NamedTuple makes the same kind of type with a class, and lets you add type hints:

python
from typing import NamedTuple

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

print(Point(3, 4))
output
Point(x=3, y=4)

Learn the idea: collections: The Stdlib's Hidden Power, Tuples: Lists That Can't Be Changed