A named tuple is a special type of tuple provided by the collections
module that allows named fields, making them more readable and self-documenting compared to regular tuples.
You can create a named tuple using collections.namedtuple()
.
from collections import namedtuple
# Define a named tuple called 'Point' with fields 'x' and 'y'
Point = namedtuple("Point", ["x", "y"])
# Create a point instance
p = Point(3, 4)
# Access values by name instead of index
print(p.x) # Output: 3
print(p.y) # Output: 4
# Named tuple is still a tuple, so it supports indexing
print(p[0]) # Output: 3
* More readable than a regular tuple (p.x
instead of p[0]
).
Feature | Named Tuple | Dictionary |
---|---|---|
Memory usage | Less (optimized like a tuple) | More (stores keys & values) |
Access speed | Faster (tuple-like) | Slightly slower |
Mutability | Immutable | Mutable |
Readability | (p.x instead of p['x'] ) |
Good, but longer syntax |
defaultdict
from collections import namedtuple
# Define a named tuple with default values
Person = namedtuple("Person", ["name", "age", "city"])
p1 = Person("Alice", 25, "New York")
print(p1.name) # Output: Alice
print(p1._asdict()) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
* Easily convert to a dictionary!
_replace()
p2 = p1._replace(age=26)
print(p2) # Output: Person(name='Alice', age=26, city='New York')
* Creates a new modified instance (since tuples are immutable).
* For lightweight, immutable data structures (e.g., coordinates, database rows).
* When you need dictionary-like access but with better performance.
* For cleaner, self-documenting code.