Introduction
Named tuples provide a way to create simple, immutable classes with named fields.
Basic Named Tuples
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y) # 10, 20
print(p[0], p[1]) # 10, 20 (indexable)
With Defaults
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
Point.__new__.__defaults__ = (0, 0) # Default values
p = Point() # (0, 0)
p = Point(5) # (5, 0)
p = Point(5, 3) # (5, 3)
Methods
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
# Convert to dictionary
p._asdict() # {'x': 10, 'y': 20}
# Replace fields
p._replace(y=30) # Point(x=10, y=30)
# Get field names
p._fields # ('x', 'y')
# Make from iterable
Point._make([10, 20]) # Point(x=10, y=20)
Practice Problems
- Create named tuple for RGB color
- Use defaults in named tuple
- Convert list of tuples to named tuples
- Implement Point3D extending Point2D
- Use namedtuple in DataFrame