Create Named Records with namedtuple
Core idea
namedtuple(typename, field_names) creates a tuple subclass, not a record instance. Call the resulting class with field values. Instances support indexing, unpacking and named attribute access, but fields cannot be reassigned.
from collections import namedtupleReading = namedtuple("Reading", ["station", "value"])r = Reading("N", 21)print(r.station, r[1])Attribute access makes the meaning of each position explicit.
Replace one field
from collections import namedtuplePoint = namedtuple("Point", "x y")p = Point(2, 4)q = p._replace(y=9)print(p.y, q.y)print(q._asdict())_replace returns a new record; _asdict returns a regular dict in Python 3.8+. These underscore-prefixed methods are documented APIs.
Intentional field assignment error
from collections import namedtuplePoint = namedtuple("Point", "x y")p = Point(2, 4)p.x = 8Fields are fixed, like tuple positions; use _replace for an updated record.
Common mistake
Tuple immutability does not make mutable field values immutable. A list stored in a field can still change.
Practice
Create a record for a room and its capacity; replace the capacity and compare both records.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Named tuple records
Check your understanding of namedtuple.
What is printed?
from collections import namedtuplePair = namedtuple("Pair", "a b")p = Pair(3, 7)print(p.b, p[0])What is printed?
from collections import namedtupleP = namedtuple("P", "x")a = P(3)b = a._replace(x=9)print(a.x,b.x)Which exception occurs?
from collections import namedtupleP = namedtuple("P", "x")p = P(1)p.x = 2What does namedtuple return?