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
namedtuple("Point", ["x", "y"])creates a new type calledPointwith two fields.- A
Pointis still a tuple: indexing (p[0]) and unpacking (x, y = p) work as usual. - Printing it shows the field names, which helps when you debug.
- Like any tuple, it cannot be changed.
p.x = 10raises anAttributeError.
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)