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.
Python code
19 linesfrom 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
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
- Use `typing.NamedTuple` class syntax for type hints and method definitions.
- 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
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.