namedtuple is one of Python’s most elegant and underrated tools in the collections module. It lets you create lightweight, immutable, readable data containers that behave like tuples but give each field a meaningful name — making your code clearer, self-documenting, and less error-prone.
Think of it as a tuple with superpowers: you can access fields by name (dot notation), get nice __repr__, use it as dictionary key, unpack it, and more — all without the overhead of a full class.
Basic Creation
from collections import namedtuple
# Create a namedtuple type
Person = namedtuple('Person', ['name', 'age', 'city'])
# Create instances (positional or keyword)
p1 = Person('Alice', 30, 'New York')
p2 = Person(name='Bob', age=28, city='London')
print(p1) # Person(name='Alice', age=30, city='New York')
print(p1.name) # Alice
print(p1[0]) # Alice (still works like tuple)
Key Advantages Over Regular Tuples
- Readability —
p.ageis much clearer thanp[1] - Self-documenting — field names make intent obvious
- Immutability — safe for dictionary keys, sets, or function returns
- Lightweight — no __dict__ overhead (memory-efficient)
- Useful methods — ._asdict(), ._replace(), ._fields, ._make()
Powerful Methods in Action
1. Convert to dict
p = Person('Charlie', 35, 'Tokyo')
print(p._asdict())
# {'name': 'Charlie', 'age': 35, 'city': 'Tokyo'}
2. Create modified copy (immutable update)
p2 = p._replace(age=36, city='Osaka')
print(p2) # Person(name='Charlie', age=36, city='Osaka')
3. Create from iterable
data = ['Dana', 29, 'Paris']
p3 = Person._make(data)
print(p3) # Person(name='Dana', age=29, city='Paris')
When to Use namedtuple in 2026
- Returning multiple values from functions (cleaner than plain tuples)
- Lightweight records (database rows, CSV lines, API responses)
- Struct-like data (points, colors, config objects)
- Keys in dicts/sets when order or immutability matters
Modern Alternatives (2026)
- dataclasses (Python 3.7+) — more features, mutable by default, better type hints
- attrs library — even more powerful (validators, converters, slots)
- typing.NamedTuple — type-annotated version for static typing
- pydantic.BaseModel — for validation + serialization
Choose namedtuple when you want maximum simplicity and immutability with minimal boilerplate. If you need mutation, validation, or rich typing, reach for dataclass or attrs instead.
Conclusion
namedtuple is a small but elegant tool that makes your code more readable and maintainable without any runtime cost. In 2026, with large codebases and strict typing, it remains a go-to for lightweight, immutable records. Use it whenever you’re tempted to return or store a plain tuple — your future self (and your teammates) will thank you.