How to Use NamedTuples for Lightweight Records in Python

Create lightweight, immutable data records with namedtuple that behave like tuples but have named fields for improved readability and access.

Easy Python 3.9+ Aug 9, 2026 OOP & classes 14 views 0 copies

Python code

19 lines
Python 3.9+
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])

x, y = p
print(x, y)

print(p._asdict())

p2 = p._replace(x=10)
print(p2)

if __name__ == "__main__":
    print("NamedTuple demo complete")

Output

stdout
Point(x=3, y=4)
3 4
3 4
3 4
{'x': 3, 'y': 4}
Point(x=10, y=4)
NamedTuple demo complete

How it works

The namedtuple factory creates a new tuple subclass with named fields, giving you both positional and attribute access. Tuples are immutable, so namedtuple instances are also immutable, ensuring data integrity. The _replace() method returns a new instance with specified fields changed, not modifying the original. _asdict() converts the namedtuple to an OrderedDict, useful for serialization or quick inspection. Being a tuple subclass, namedtuples are memory-efficient and support all tuple operations like unpacking and indexing.

Common mistakes

  • Assuming namedtuple fields are mutable — they're not, so use `_replace()` to create new instances.
  • Forgetting to import namedtuple from collections, leading to NameError.
  • Confusing `_replace()` with in-place modification — it returns a new object.

Variations

  1. Use `typing.NamedTuple` class syntax for type hints and method definitions.
  2. Use `dataclasses` when you need mutable records with default values and methods.

Real-world use cases

  • Returning multiple values from a function with readable field names for better code clarity.
  • Storing configuration or sensor data as immutable records that are easy to serialize and deserialize.
  • Modeling lightweight database rows or API responses without the overhead of full classes.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.