Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 8 · Lightweight Records with`namedtuple`

Lightweight Records with namedtuple

Sometimes you need tiny, efficient record types to represent lines in a dataset—coordinates, database rows, user entries, etc. A tuple is compact, but numbered fields can be hard to read. A small class is another valid choice; namedtuple offers a concise record with named fields. Python’s namedtuple solves this by acting as a factory function that creates lightweight, attribute-based record classes.

Its signature:

namedtuple(typename, field_names)

Where field_names may be a list or a space-separated string.

A geographical example illustrates the idea:

from collections import namedtuple

Location = namedtuple("Location", ["city", "lat", "lon"])
paris = Location("Paris", 48.8566, 2.3522)

print(paris.city, paris.lat)
Listing 353 — Lightweight Records with namedtuple

Output

Paris 48.8566

This prints the city name and its latitude using attribute access rather than tuple indices, showing how namedtuple makes small records both readable and convenient.

Representing rows looks even more natural:

Person = namedtuple("Person", ["name", "age", "city"])
records = [
    Person("Alice", 30, "Berlin"),
    Person("Bob", 25, "Munich"),
]

print("Name       | Age | City")
print("-" * 28)
for r in records:
    print(f"{r.name:<10} | {r.age:<3} | {r.city}")
Listing 354 — Lightweight Records with namedtuple

Output

Name       | Age | City
----------------------------
Alice      | 30  | Berlin
Bob        | 25  | Munich

Here the rows are displayed in a simple table-like form, similar to how database results often look. In data science workflows, where each row holds fixed, simple attributes,namedtuple provides clarity and speed without the verbosity of full class definitions.